简单的问题,如果你使用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 = "" })
其他回答
value="0"将为@Html设置默认值。TextBoxfor
区分大小写 “v”应该大写
下面是工作示例:
@Html.TextBoxFor(m => m.Nights,
new { @min = "1", @max = "10", @type = "number", @id = "Nights", @name = "Nights", Value = "1" })
事实证明,如果你没有在控制器中指定Model到View方法,它就不会用默认值为你创建一个对象。
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Create()
{
// Loads default values
Instructor i = new Instructor();
return View("Create", i);
}
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Create()
{
// Does not load default values from instructor
return View("Create");
}
对于。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");
试试这个:
<%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>
注意@Value有一个大写V
这为我工作,在这种方式,我们设置默认值为空字符串
@Html.TextBoxFor(m => m.Id, new { @Value = "" })