在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="" />
我注意到“input”标记中有两个Value属性:
Value="0"
和value=""
如何使它只显示一个值属性?
答案 0 :(得分:7)
使用TextBox而不是TextBoxFor
@Html.TextBox("WEIGHT", Model.WEIGHT ?? "0", new {...})
或者如果WEIGHT是一个空字符串
@Html.TextBox("WEIGHT", Model.WEIGHT == "" ? "0" : Model.WEIGHT, new {...})
答案 1 :(得分:5)
这似乎是默认行为。如果您真的想避免使用双值属性,最好通过在控制器类的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" />
答案 2 :(得分:3)
您已明确声明Value
,而不是value
。
尝试:
@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", @class = "mustInputText noime w50", maxlength = "8", @value = "0", rule = "InputOnlyNum" })
答案 3 :(得分:1)
未经测试,但请尝试TextBox
而不是TextBoxFor
,因为它有一个重载,可以将值作为第二个参数传递。
@Html.TextBox(p => p.WEIGHT, "0",
new { tabindex = "140", @class = "mustInputText noime w50",
maxlength = "8", @Value = "0", rule = "InputOnlyNum" })
另一个选项是在初始化WEIGHT的模型类的构造函数中设置默认值。
答案 4 :(得分:0)
也许这个?未经测试。
@Html.TextBoxFor(p => (p.WEIGHT==null ? 0 : p.WEIGHT), new { tabindex = "140",
@class = "mustInputText noime w50",
maxlength = "8",
rule = "InputOnlyNum" })
答案 5 :(得分:0)
@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", @class = "mustInputText noime w50", maxlength = "8",
@value = model.WEIGHT==null?"0":model.WEIGHT, rule = "InputOnlyNum" })