MVC中@Html.DisPlayFor(model=>model.newsName)和 @Model.newsName的区别

MVC中,在Controllers查询到数据,返回一个实体给View并显示,能够用@Html.DisPlayFor(model=>model.newsName)和 @Model.newsName这两种方式显示某个字段数据(如newsName),可是,这二者是用区别的,即若是Controllers中没有查询到数据,则会返回一个值为null的实体(固然你能够进行判断,不返回null到view中),用 @Model.newsName这种方式显示的话会报错。下面我就用一个实例来演示一下:html

Controllers 代码:数据库

复制代码
public ActionResult Details(string id)
{
   newsInfo newsCont=new newsInfo();
   int nid = Convert.ToInt32(id);
   if (!string.IsNullOrEmpty(id))
   {
newsCont = db.newsInfo.Find(nid); //如何查不到数据,则db.newsInfo.Find(nid)返回值为null } else {
Response.Redirect("/News/");
} return View(newsCont); }
复制代码

Views 代码:spa

复制代码
@model MvcWeb.Models.newsInfo

<div class="rContent fl">
        <div class="cName fw tac">@Html.DisplayFor(model => model.newsName)</div>  <!--@Html.DisplayFor方法--> 
        <div class="cTime tac">阅读数:@Model.reads 发布时间:@Model.inDate</div>   <!--@Model.reads方法--> 
        <div class="content fl">@Model.newsContent</div> 
</div>
复制代码

运行程序,我故意给一个数据库表中不存在的id,报错以下图:code

从上图报错地方(红色部分)能够看出用 @Model.newsName这种方式显示的话会报错!因此用@Html.DisPlayFor(model=>model.newsName)能够避免!htm

至于个中缘由,我还不甚明白,各位大神也能够指教一下。blog

 

摘自:http://www.cnblogs.com/qk2014/p/3994384.htmlstring

相关文章
相关标签/搜索