是什么Html.Hidden和Html.HiddenFor之间的区别 [英] What is the difference between Html.Hidden and Html.HiddenFor

查看:2291
本文介绍了是什么Html.Hidden和Html.HiddenFor之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以找到在MSDN上的Html.HiddenFor一个很好的定义,但我可以找到Html.Hidden的唯一的事情是与它有问题。

I can find a good definition for Html.HiddenFor on MSDN but the only thing I can find on Html.Hidden is related to problems it has.

有人可以给我一个很好的定义和示例。

Can someone give me a good definition and an example.

推荐答案

大多数MVC辅助方法有XXXFor变体。它们意在结合使用一个具体模型类。我们的想法是,让助手来推导基于您在拉姆达指定属性的形式输入控制适当的名属性。这意味着,你能消除魔术字符串,否则你将不得不使用你的看法关联模型属性。例如:

Most of the MVC helper methods have a XXXFor variant. They are intended to be used in conjunction with a concrete model class. The idea is to allow the helper to derive the appropriate "name" attribute for the form-input control based on the property you specify in the lambda. This means that you get to eliminate "magic strings" that you would otherwise have to employ to correlate the model properties with your views. For example:

Html.Hidden("Name", "Value")

将导致:

<input type="Name" value="Value" />

在你的控制器,你可能有这样一个动作:

In your controller, you might have an action like:

[HttpPost]
public ActionResult MyAction(MyModel model) 
{
}

和像模特:

public class MyModel 
{
    public string Name { get; set; }
}

原始 Html.Hidden 我们上面使用将获得相关的名称在模型属性。然而,这有点让人反感的值名称为属性必须使用字符串(姓名)来指定。如果重命名名称属性上的型号,code将打破,误差会有些很难弄清楚。在另一方面,如果你使用 HiddenFor ,你得到的保护,不得:

The raw Html.Hidden we used above will get correlated to the Name property in the model. However, it's somewhat distasteful that the value "Name" for the property must be specified using a string ("Name"). If you rename the Name property on the Model, your code will break and the error will be somewhat difficult to figure out. On the other hand, if you use HiddenFor, you get protected from that:

Html.HiddenFor(x => x.Name, "Value");

现在,如果重命名名称属性,你会得到这表明财产不能找到一个明确的运行时错误。此外,你得到的静态分析的其他利益,如获取成员的下拉键入后面的x。

Now, if you rename the Name property, you will get an explicit runtime error indicating that the property can't be found. In addition, you get other benefits of static analysis, such as getting a drop-down of the members after typing x..

这篇关于是什么Html.Hidden和Html.HiddenFor之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆