Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why DisplayFor does not post values to Action Method?

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 ?

like image 933
SMC Avatar asked Dec 01 '22 20:12

SMC


2 Answers

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?

like image 199
ataravati Avatar answered Dec 04 '22 09:12

ataravati


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>

enter image description here

like image 30
andres descalzo Avatar answered Dec 04 '22 09:12

andres descalzo