首页 文章

如何使用Html.TextBoxFor设置默认值?

提问于
浏览
182

简单的问题是,如果您使用ASP.NET MVC Framework 1中的Html Helper,则很容易在文本框上设置默认值,因为存在重载 Html.TextBox(string name, object value) . 当我尝试使用Html.TextBoxFor方法时,我的第一个猜测是尝试以下哪些不起作用:

<%: Html.TextBoxFor(x => x.Age, new { value = "0"}) %>

我现在应该坚持使用Html.TextBox(字符串,对象)吗?

12 回答

  • 7

    这是我解决它的方式 . 如果您也使用它进行编辑,则此方法有效 .

    @Html.TextBoxFor(m => m.Age, new { Value = Model.Age.ToString() ?? "0" })
    
  • 8

    如果您有编辑和添加的部分页面表单,那么我使用默认值为 0 的技巧是执行以下操作:

    @Html.TextBox("Age", Model.Age ?? 0)
    

    这样,如果未设置,则为 0 ,如果存在,则为实际年龄 .

  • 5

    这对我有用,这样我们将默认值设置为空字符串

    @Html.TextBoxFor(m => m.Id, new { @Value = "" })
    
  • 55

    这对我有用

    @Html.TextBoxFor(model => model.Age, htmlAttributes: new { @Value = "" })
    
  • 0

    也尝试这个,即删除new {}并用string替换它 .

    <%: Html.TextBoxFor(x => x.Age,"0") %>
    
  • 16

    你可以试试这个

    <%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>
    
  • 20

    这适用于MVC3和MVC4

    @Html.TextBoxFor(m => m.Age, new { @Value = "12" })
    

    如果你想让它成为一个隐藏的领域

    @Html.TextBoxFor(m => m.Age, new { @Value = "12",@type="hidden" })
    
  • 5

    事实证明,如果您没有在控制器中为View方法指定Model,则它不会为您创建具有默认值的对象 .

    [AcceptVerbs(HttpVerbs.Get)]
    public ViewResult Create()
    {
      // Loads default values
      Instructor i = new Instructor();
      return View("Create", i);
    }
    
    [AcceptVerbs(HttpVerbs.Get)]
    public ViewResult Create()
    {
      // Does not load default values from instructor
      return View("Create");
    }
    
  • 5

    默认值将是 Model.Age 属性的值 . 这就是重点 .

  • 326

    你可以简单地做:

    <%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>
    

    或者更好,如果模型为空,这将切换到默认值'0',例如,如果编辑和创建具有相同的视图:

    @Html.TextBoxFor(x => x.Age, new { @Value = (Model==null) ? "0" : Model.Age.ToString() })
    
  • 29

    value =“0”将为@ Html.TextBoxfor设置defualt值

    其区分大小写的“v”应该是资本

    以下是工作示例:

    @Html.TextBoxFor(m => m.Nights, 
        new { @min = "1", @max = "10", @type = "number", @id = "Nights", @name = "Nights", Value = "1" })
    
  • 10

    使用 @Value 是一个hack,因为它输出两个属性,例如:

    <input type="..." Value="foo" value=""/>
    

    你应该这样做:

    @Html.TextBox(Html.NameFor(p => p.FirstName).ToString(), "foo")
    

相关问题