Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {                 $("#personal-details-form").trigger('reset');                 sessionStorage.setItem("personalDetailsVisitCount", "1");             }             else {                 var validator = $("#personal-details-form").validate();                 validator.form();                 cat.personaldetails.validate();             }         });     </script> }  } 

Thank you

like image 678
user845405 Avatar asked Feb 04 '15 04:02

user845405


People also ask

Why is ViewBag null?

ViewBag doesn't require any type of typecasting for complex data type. ViewBag also has a short life i.e. Its value becomes null when redirection occurs because its life lies only during current request. This is because the aim of ViewBag is to provide a way to transfer/pass data from controllers and views.

What is the type of the ViewBag property?

In general, ViewBag is a way to pass data from the controller to the view. It is a type object and is a dynamic property under the controller base class.

How do you show messages in ViewBag?

In this example, we have created a sample form page, We are using ViewBag to display message in the View after button click. Open Visual Studio. Click on the file in the menu and select new Project . Select new project type.


1 Answers

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.

like image 185
Mairaj Ahmad Avatar answered Sep 28 '22 12:09

Mairaj Ahmad