简体   繁体   中英

MVC Customizing display template: Model.Value vs @ViewData.Model

I've seen two "Display templates customezing" examples.

In the 1. example programmer use Model.Value and in the 2. example he use @ViewData.Model.- See below

Exampel 1 (DateTime view:)

@model DateTime?
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd/MM/yyyy") : "", new { @class = "ka_" })

Example 2:

<a href="@ViewData.Model" target="_blank">@ViewData.Model<a/>

What is the difference between them ?

What to select ?

In most cases you use both in your views. The model specifies the data for you're main view. It's the data that is created by the controller action. The ViewData dictionary is normally populated by other components.

Let's take for example an Product (view)model. A product would have a price, a description, a sku and in most cases a stock indication.

You're Product (view)model does not contain data any user information, website navigational data. That data is placed in the ViewData dictionary by other components and can be used by (parent) views to render the full page.

A bit offtopic, but at our company we have a very strict rules about what a view is allowed to do. In short is it not allowed to change/modify any data (not even the page title!) or to retrieve any data. The only code allowed in our views are conditional constructs and calls to helper methods. It helps if new developers on the team start with view engines that have no an 'eval' constructs like SuperSimpleViewEngine (from NancyFx) or XsltViewEngine. Razor and WebForms make it to easy to 'cheat'..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM