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

三世轮回 提交于 2019-12-05 11:19:20

问题


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


回答1:


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

@if (ViewBag.UserExists != null)
{
    <h3>@ViewBag.UserExists</h3>
}



回答2:


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>
           }



回答3:


The code could be further simplified to :

<h3>
   @(ViewBag.UserExists??"USER DOES NOT EXIST")
</h3>


来源:https://stackoverflow.com/questions/6935828/viewbag-check-to-see-if-item-exists-and-write-out-html-and-value-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!