简单的问题,如果从ASP.NET MVC框架1使用HTML辅助很容易设置的默认值上一个文本框,因为有一个过载Html.TextBox(string name, object value)
。当我尝试使用Html.TextBoxFor方法,我的第一个猜测是尝试,没有工作的情况如下:
<%: Html.TextBoxFor(x => x.Age, new { value = "0"}) %>
如果我只是Html.TextBox(字符串对象)坚持现在?
你可以试试这个
<%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>
这个工作对我来说,这样我们设定的默认值空字符串
@Html.TextBoxFor(m => m.Id, new { @Value = "" })
如果你有两个编辑和添加的部分页面表单,然后我用默认值0
,关键是要做到以下几点:
@Html.TextBox("Age", Model.Age ?? 0)
这样,这将是0
如果没有设置或者如果它存在的实际年龄。
试试这个也是,这是消除新的{}用绳子代替。
<%: Html.TextBoxFor(x => x.Age,"0") %>
这应该适用于MVC3和MVC4
@Html.TextBoxFor(m => m.Age, new { @Value = "12" })
如果你希望它是一个隐藏字段
@Html.TextBoxFor(m => m.Age, new { @Value = "12",@type="hidden" })
事实证明,如果不指定型号到控制器内的视图方法,它不会为你创建一个对象使用默认值。
[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");
}
默认值将是Model.Age
属性的值。这是一种整点。
你可以简单地做:
<%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>
或更好,这会,如果你有两个编辑和创建相同的视图切换到默认值“0”如果模型为null,例如:
@Html.TextBoxFor(x => x.Age, new { @Value = (Model==null) ? "0" : Model.Age.ToString() })
值=“0”将设置默认值@ Html.TextBoxfor
其区分大小写的“V”应该是资本
下面是工作示例:
@Html.TextBoxFor(m => m.Nights,
new { @min = "1", @max = "10", @type = "number", @id = "Nights", @name = "Nights", Value = "1" })
使用@Value
是一个黑客,因为它输出两个属性,例如:
<input type="..." Value="foo" value=""/>
你应该这样做,而不是:
@Html.TextBox(Html.NameFor(p => p.FirstName).ToString(), "foo")
下面是我如何解决它。这个作品,如果你也用这个编辑。
@Html.TextBoxFor(m => m.Age, new { Value = Model.Age.ToString() ?? "0" })
这项工作对我来说
@Html.TextBoxFor(model => model.Age, htmlAttributes: new { @Value = "" })