Html. HiddenFor 是做什么的?

尽管我已经阅读了 Html.HiddenFor 上的文档,但是我还没有理解它用于..。

有人能解释一下它的用途并举个简短的例子吗?

在代码中这些帮助者应该去哪里?

144019 次浏览

It creates a hidden input on the form for the field (from your model) that you pass it.

It is useful for fields in your Model/ViewModel that you need to persist on the page and have passed back when another call is made but shouldn't be seen by the user.

Consider the following ViewModel class:

public class ViewModel
{
public string Value { get; set; }
public int Id { get; set; }
}

Now you want the edit page to store the ID but have it not be seen:

<% using(Html.BeginForm() { %>
<%= Html.HiddenFor(model.Id) %><br />
<%= Html.TextBoxFor(model.Value) %>
<% } %>

This results in the equivalent of the following HTML:

<form name="form1">
<input type="hidden" name="Id">2</input>
<input type="text" name="Value" value="Some Text" />
</form>

And to consume the hidden ID input back on your Edit action method:

[HttpPost]
public ActionResult Edit(FormCollection collection)
{
ViewModel.ID = Convert.ToInt32(collection["ID"]);
}

The Use of Razor code @Html.Hidden or @Html.HiddenFor is similar to the following Html code

 <input type="hidden"/>

And also refer the following link

https://msdn.microsoft.com/en-us/library/system.web.mvc.html.inputextensions.hiddenfor(v=vs.118).aspx

Like a lot of functions, this one can be used in many different ways to solve many different problems, I think of it as yet another tool in our toolbelts.

So far, the discussion has focused heavily on simply hiding an ID, but that is only one value, why not use it for lots of values! That is what I am doing, I use it to load up the values in a class only one view at a time, because html.beginform creates a new object and if your model object for that view already had some values passed to it, those values will be lost unless you provide a reference to those values in the beginform.

To see a great motivation for the html.hiddenfor, I recommend you see Passing data from a View to a Controller in .NET MVC - "@model" not highlighting