在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=""
如何使它只显示一个值的属性?
Answer 1:
使用文本框,而不是TextBoxFor
@Html.TextBox("WEIGHT", Model.WEIGHT ?? "0", new {...})
或者,如果体重是一个空字符串
@Html.TextBox("WEIGHT", Model.WEIGHT == "" ? "0" : Model.WEIGHT, new {...})
Answer 2:
这似乎是默认行为。 如果你真的想避免双重价值属性,最好通过在控制器类的创建方法设置默认值遵循清洁的方式。 这是继MVC模式的思想。
//GET
public ActionResult CreateNewEntity()
{
YourEntity newEntity= new YourEntity ();
newEntity.WEIGHT= 0;
return View(newEntity);
}
然后在你看来,你将不需要再使用值属性:
@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" />
Answer 3:
那么您已经明确规定Value
,而不是value
。
尝试:
@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", @class = "mustInputText noime w50", maxlength = "8", @value = "0", rule = "InputOnlyNum" })
Answer 4:
未经检验的,但尝试TextBox
,而不是TextBoxFor
,因为它传递的值作为第二个参数的重载。
@Html.TextBox(p => p.WEIGHT, "0",
new { tabindex = "140", @class = "mustInputText noime w50",
maxlength = "8", @Value = "0", rule = "InputOnlyNum" })
另一种选择是在初始化WEIGHT模型类的构造函数设置默认值。
Answer 5:
也许这? 未经测试。
@Html.TextBoxFor(p => (p.WEIGHT==null ? 0 : p.WEIGHT), new { tabindex = "140",
@class = "mustInputText noime w50",
maxlength = "8",
rule = "InputOnlyNum" })
Answer 6:
@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", @class = "mustInputText noime w50", maxlength = "8",
@value = model.WEIGHT==null?"0":model.WEIGHT, rule = "InputOnlyNum" })
文章来源: Default value for TextBoxFor in ASP.NET MVC