简单的问题,如果你使用ASP的Html Helper。NET MVC框架1很容易在文本框上设置默认值,因为有一个重载Html。文本框(字符串名称,对象值)。当我尝试使用Html时。TextBoxFor方法,我的第一个猜测是尝试以下不工作:

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

我应该继续使用Html吗?文本框(字符串,对象)现在?


当前回答

试试这个:

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

注意@Value有一个大写V

其他回答

这对我很有用

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

你可以简单地做:

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

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

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

试试这个,也就是删除新的{},并将其替换为字符串。

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

对于。net core 5,在htmlAttributes中设置值似乎不起作用。但是你可以使用workaround:

var ageTextBox = (TagBuilder) Html.TextBoxFor(x => x.Age);
ageTextBox.Attributes.Remove("value");
ageTextBox.Attributes.Add("value", "value you want to set");

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

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

你应该这样做:

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