36

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

SteveC
  • 15,808
  • 23
  • 102
  • 173
Dietpixel
  • 9,983
  • 11
  • 28
  • 33

3 Answers3

93

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

@if (ViewBag.UserExists != null)
{
    <h3>@ViewBag.UserExists</h3>
}
lahsrah
  • 9,013
  • 5
  • 37
  • 67
  • 1
    Another option would be to use `@Html.Raw("

    " + ViewBag.UserExists + "

    ")` as I believe the above will not render as desired if `ViewBag.UserExists` contains any HTML.
    – dav_i May 09 '13 at 08:35
  • I noticed this, and I had a error and realized since I was inside a form , I need to drop the "@" if (ViewBag.IsValid != null) { –  Jul 22 '13 at 07:10
  • 2
    Don't use Html.Raw unless you EXPECT there to be safe HTML, otherwise you are exposing yourself to exploitation. If you are new to Razor one good rule of thumb is if you are writing `Response.Write("...")` then you're doing it wrong. – kingdango Dec 19 '13 at 13:32
1

May be useful to some one who need to check NULL as well data type of ViewBag

if (ViewBag.MyBag != null & ViewBag.MyBag is string) //int or Foo or anyObject
            {
                <div class="row">
                    <br />
                    <div class="alert alert-danger col-sm-offset-2 col-md-8">
                        @ViewBag.MyBag
                    </div>
                </div>
           }
Vijai
  • 2,369
  • 3
  • 25
  • 32
0

The code could be further simplified to :

<h3>
   @(ViewBag.UserExists??"USER DOES NOT EXIST")
</h3>
Nishanth Shaan
  • 1,422
  • 15
  • 18