Check if ViewBag is null or doesn't exist
ASP.NET MVC uses ViewBag to store some data from Controller and than accessed in View like you can save UserName in ViewBag who is logged in to your website and than display it in view.
Sometimes you need to check if ViewBag exists or it is not null than execute your next piece of code. Let's take an example.
Controller Code
View Code
Here if ViewBag.UserName is not null than label will be rendered with username. If it is null the code will not execute. So you can easily check for a ViewBag Property and execute your code.
Sometimes you need to check if ViewBag exists or it is not null than execute your next piece of code. Let's take an example.
Controller Code
public ActionResult Index() { ViewBag.UserName = "John"; return View(); }
View Code
@if (ViewBag.UserName != null)
{
<label>@ViewBag.UserName</label>; }
Here if ViewBag.UserName is not null than label will be rendered with username. If it is null the code will not execute. So you can easily check for a ViewBag Property and execute your code.
www.familystatus.in
ReplyDeleteNice Articles
ReplyDeletefamilystatus
familystatus
ReplyDelete