简单的问题,如果你使用ASP的Html Helper。NET MVC框架1很容易在文本框上设置默认值,因为有一个重载Html。文本框(字符串名称,对象值)。当我尝试使用Html时。TextBoxFor方法,我的第一个猜测是尝试以下不工作:
<%: Html.TextBoxFor(x => x.Age, new { value = "0"}) %>
我应该继续使用Html吗?文本框(字符串,对象)现在?
简单的问题,如果你使用ASP的Html Helper。NET MVC框架1很容易在文本框上设置默认值,因为有一个重载Html。文本框(字符串名称,对象值)。当我尝试使用Html时。TextBoxFor方法,我的第一个猜测是尝试以下不工作:
<%: Html.TextBoxFor(x => x.Age, new { value = "0"}) %>
我应该继续使用Html吗?文本框(字符串,对象)现在?
当前回答
这对我很有用
@Html.TextBoxFor(model => model.Age, htmlAttributes: new { @Value = "" })
其他回答
这对我很有用
@Html.TextBoxFor(model => model.Age, htmlAttributes: new { @Value = "" })
value="0"将为@Html设置默认值。TextBoxfor
区分大小写 “v”应该大写
下面是工作示例:
@Html.TextBoxFor(m => m.Nights,
new { @min = "1", @max = "10", @type = "number", @id = "Nights", @name = "Nights", Value = "1" })
如果你有一个用于编辑和添加的部分页面表单,那么我使用的将默认值设置为0的技巧是:
@Html.TextBox("Age", Model.Age ?? 0)
这样,如果未设置它将为0,如果存在则为实际年龄。
你可以简单地做:
<%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>
或者更好的是,如果模型为空,这将切换到默认值'0',例如,如果你有相同的视图用于编辑和创建:
@Html.TextBoxFor(x => x.Age, new { @Value = (Model==null) ? "0" : Model.Age.ToString() })
这应该适用于MVC3和MVC4
@Html.TextBoxFor(m => m.Age, new { @Value = "12" })
如果你想让它成为一个隐藏字段
@Html.TextBoxFor(m => m.Age, new { @Value = "12",@type="hidden" })