The difference between @html.displayfor (Model=>model.newsname) and @Model. Newsname in MVC

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.