zoukankan      html  css  js  c++  java
  • 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!

  • 相关阅读:
    搜索引擎代码资源
    shell十三问(很不错的shell解释)
    Export/Import 使用技巧与常见错误
    利用java实现数据结构中常用的插入排序和快速排序算法
    java23种设计模式与追MM
    sqlldr使用小结(zt)
    排序算法的java实现的网址链接
    Rdesktop与Window相联
    java抽取word,pdf的四种武器
    常用数据库JDBC连接写法
  • 原文地址:https://www.cnblogs.com/chucklu/p/15561223.html
Copyright © 2011-2022 走看看