In MVC, the controllers queries the data, returns an entity to the view and displays it, can be used @html.displayfor (model=>model.newsname) and @ Model.newsname these two ways of displaying a field data (such as Newsname), however, the two are different, that is, if there is no query to the data in controllers, then a value of NULL is returned (of course you can judge, do not return null to view), with @Model. Newsname this way, the error will be indicated. I'll use an example to illustrate the following:
Controllers Code:
Public ActionResult Details (string id) { newsinfo newscont=new newsinfo (); int nid = Convert.ToInt32 (id); if (!string. IsNullOrEmpty (ID)) {
Newscont = Db.newsInfo.Find (nid); How data is not found, the Db.newsInfo.Find (NID) return value is null } Else
} return View (Newscont);}
Views Code:
@model mvcweb.models.newsinfo<div class= "rcontent fl" > <div class= "cName FW tac" > @Html. Displayfor ( Model = model.newsname) </div> <[email Protected] Method-- <div class= "CTime TAC" > reads: @Model. Reads release time: @Model .indate</div> <[email Protected] Method--- <div class= "content fl" > @Model .newscontent</div> </div>
Run the program, I deliberately give a database table does not exist in the ID, error such as:
From the Error place (Red section) can be seen with @Model. Newsname this way, it will be an error! So with @html.displayfor (model=>model.newsname) can be avoided!
As for the reasons, I do not quite understand that the great God can also give advice.
Excerpt from: http://www.cnblogs.com/qk2014/p/3994384.html
The difference between @html.displayfor (Model=>model.newsname) and @Model. Newsname in MVC