Why DisplayFor does not post values to Action Method?

孤街醉人 提交于 2020-01-14 10:26:08

问题


When we post the form using below to Action Method, we can see the View Model values in Parameter.

@Html.EditorFor(model => model.Foo)

When we post the form using below to Action Method, we can't see the View Model values in Parameter.

@Html.DisplayFor(model => model.Foo)

So, in later case, w could us Hidden Fields. So, I think, w should not us DisplayFor when it comes o post form values.

Question : Why DisplayFor does not post values to Action Method? Can we discuss the internal mechanism for this ?


回答1:


see the html rendering. does not have the attribute name. or not an input tag. the form tag only send tag elements input, select, textarea,... that have the attribute name. For example:

<form...>
   <input id="lastname" name="lastname" />
</form>

not this:

<form...>
   <input id="lastname" />
</form>




回答2:


Because DisplayFor does not render an input field for the property. That's why it's called DisplayFor, and not EditorFor. It's meant to be used to display the property to the user.

As an example, let's say you have a string property called Name with the value of "John" in your Model. In that case, here is how Html.EditorFor and Html.DisplayFor are rendered for that property on the page:

@Html.EditorFor(model => model.Name)

This will be rendered as:

<input name="Name" id="Name" type="text" value="John" /> 

But,

@Html.DisplayFor(model => model.Name)

will be rendered as:

John

By the way, Html.HiddenFor will render a hidden field on your page which will be posted to your Controller. With the above example,

@Html.HiddenFor(model => model.Name)

will be rendered like this:

<input name="Name" id="Name" type="hidden" value="John" />

You use EditorFor when you want the user to enter data into your page, use DisplayFor when you want to display a read-only data to the user, and use HiddenFor when you want to post the data to the Controller when the form is submitted, but the data is not supposed to be edited by and visible to the user. An example is an ID field that's not edited by the user, but you need it in your form.

Have a look at this post: What is the @Html.DisplayFor syntax for?



来源:https://stackoverflow.com/questions/18422637/why-displayfor-does-not-post-values-to-action-method

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