5

在 ASP.NET MVC 中,我编写了下面的代码来给文本框一个初始值:

@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", 
                                      @class = "mustInputText noime  w50", 
                                      maxlength = "8", @Value = "0", 
                                      rule = "InputOnlyNum" })

而Html源码如下:

<input Value="0" class="mustInputText noime  w50" id="WEIGHT" maxlength="8" 
    name="WEIGHT" rule="InputOnlyNum" tabindex="140" type="text" value="" />

我注意到“输入”标签中有两个值属性: Value="0"value=""

如何让它只显示一个值属性?

4

6 回答 6

7

使用 TextBox 而不是 TextBoxFor

@Html.TextBox("WEIGHT", Model.WEIGHT ?? "0", new {...})

或者如果 WEIGHT 是一个空字符串

@Html.TextBox("WEIGHT", Model.WEIGHT == "" ? "0" : Model.WEIGHT, new {...})
于 2013-05-10T16:00:09.453 回答
5

这似乎是默认行为。如果你真的想避免双重Value属性,最好遵循更简洁的方式,在控制器类的create方法中设置默认值。这遵循了 MVC 模式的意识形态。

//GET
public ActionResult CreateNewEntity()
{
    YourEntity newEntity= new YourEntity ();
    newEntity.WEIGHT= 0;

    return View(newEntity);
}

然后在您看来,您将不再需要使用 value 属性:

@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", 
                                      @class = "mustInputText noime  w50",     
                                      maxlength = "8", 
                                      rule = "InputOnlyNum" })

您生成的 html 是:

<input class="mustInputText noime  w50" 
       id="WEIGHT" 
       maxlength="8" 
       name="WEIGHT" 
       rule="InputOnlyNum" 
       tabindex="140" 
       type="text" 
       value="0" />
于 2013-05-10T01:17:37.823 回答
3

好吧,您已经明确表示Value,不是value

尝试:

 @Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", @class = "mustInputText noime  w50", maxlength = "8", @value = "0", rule = "InputOnlyNum" })
于 2013-05-07T08:00:34.427 回答
0

未经测试,但尝试TextBox代替TextBoxFor,因为它具有将值作为第二个参数传递的重载。

@Html.TextBox(p => p.WEIGHT, "0",
    new { tabindex = "140", @class = "mustInputText noime  w50", 
          maxlength = "8", @Value = "0", rule = "InputOnlyNum" })

另一个选项是在初始化 WEIGHT 的模型类的构造函数中设置默认值。

于 2013-05-10T01:10:53.663 回答
0

也许这个?未经测试。

@Html.TextBoxFor(p => (p.WEIGHT==null ? 0 : p.WEIGHT), new { tabindex = "140", 
      @class = "mustInputText noime  w50", 
      maxlength = "8",  
      rule = "InputOnlyNum" })
于 2013-05-10T15:47:05.847 回答
0
   @Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", @class = "mustInputText noime  w50", maxlength = "8",
 @value =  model.WEIGHT==null?"0":model.WEIGHT, rule = "InputOnlyNum" })
于 2017-01-19T06:25:52.273 回答