What is the difference between Html.Hidden and Html.HiddenFor
What is the difference between Html.Hidden and Html.HiddenFor
回答1
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")
Will result in:
<input id="Name" name="Name" type="hidden" value="Value">
In your controller, you might have an action like:
[HttpPost]
public ActionResult MyAction(MyModel model)
{
}
And a model like:
public class MyModel
{
public string Name { get; set; }
}
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");
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.
.
回答2
The Html.Hidden creates a hidden input but you have to specify the name and all the attributes you want to give that field and value. The Html.HiddenFor
creates a hidden input for the object that you pass to it, they look like this:
Html.Hidden("yourProperty",model.yourProperty);
Html.HiddenFor(m => m.yourProperty)
In this case the output is the same!
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2020-11-16 TLS Handshake Protocol RFC 5246 (TLS 1.2)
2017-11-16 Transformation in kentico
2017-11-16 Checkmarx VisualStudio plugin installation process.
2016-11-16 NavBarControl