Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Viewbag check to see if item exists and write out html and value error

I'm using razor syntax and I want to check to see if certain ViewBag values are set before I spit out the html. If a value is set then I want to write it out. If not I want it to do nothing.

@if (ViewBag.UserExists != null)     { Response.Write(String.Format("<h3>{0}</h3>", ViewBag.UserExists)); } 

This doesn't appear to be working correctly. The code shows up on top of another h2 I have above the code above. I have two register controller methods. One is the get and the other accepts the post. If the user exists I am setting a ViewBag item that needs to be displayed to the user.

Thanks

like image 420
Dietpixel Avatar asked Aug 04 '11 03:08

Dietpixel


People also ask

How do you write if condition in razor view?

The If Condition The if statement returns true or false, based on your test: The if statement starts a code block. The condition is written inside parenthesis. The code inside the braces is executed if the test is true.

What if the ViewBag property name matches with the key of ViewData?

It will throw a runtime exception, if the ViewBag property name matches with the key of ViewData.

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.


1 Answers

Don't use Response.Write. Instead do this:

@if (ViewBag.UserExists != null) {     <h3>@ViewBag.UserExists</h3> } 
like image 87
lahsrah Avatar answered Oct 02 '22 09:10

lahsrah