user845405 user845405 - 8 months ago 169
C# Question

How to check if ViewBag property is null or not exists

I have a requirement to execute a script in document.ready function if viewbag property is null or not exists. Below is the code i wrote to check if viewbag property not exists.

i used recommned approached where you @ViewBag.Property!=null but when i do that i get an error saying name property does not exist in current context,

@section scripts {

@if ((bool)ViewData.ContainsKey("FormSubmitFlag") == false)
<script type="text/javascript">
$(document).ready(function () {

var pageVisitCount = sessionStorage.getItem("personalDetailsVisitCount");
if (pageVisitCount == null) {
sessionStorage.setItem("personalDetailsVisitCount", "1");
else {
var validator = $("#personal-details-form").validate();


Thank you


You can check for null and execute your script.

@if (ViewBag.YourKey== null)
 //your code   

This will check that ViewBag.YourKey is null if you want to check it for not null you can change the if condition.