如何用Html.TextBoxFor设置默认值?
简单的问题是,如果使用ASP.NET MVC Framework 1中的Html Helper,则很容易在文本框上设置默认值,因为存在重载Html.TextBox(string name, object value) 。 当我尝试使用Html.TextBoxFor方法时,我的第一个猜测是尝试以下哪个不起作用: 
 <%: Html.TextBoxFor(x => x.Age, new { value = "0"}) %> 
我现在应该坚持Html.TextBox(string,对象)吗?
你可以试试这个
 <%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %> 
这应该适用于MVC3和MVC4
  @Html.TextBoxFor(m => m.Age, new { @Value = "12" }) 
如果你想要它是一个隐藏的领域
  @Html.TextBoxFor(m => m.Age, new { @Value = "12",@type="hidden" }) 
事实certificate,如果你没有在你的控制器的View方法中指定Model,它不会为你使用默认值创build一个对象。
 [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"}) %> 
或更好,如果模型为null,则会切换到默认值“0”,例如,如果您在编辑和创build时都有相同的视图:
 @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" }) 
 如果您有编辑和添加的部分页面表单,那么我使用默认值为0的技巧是执行以下操作: 
 @Html.TextBox("Age", Model.Age ?? 0) 
 这样,如果未设置或实际年龄(如果存在),它将为0 。 
这工作对我来说,这样我们将默认值设置为空string
 @Html.TextBoxFor(m => m.Id, new { @Value = "" }) 
这为我工作
 @Html.TextBoxFor(model => model.Age, htmlAttributes: new { @Value = "" }) 
试试这也是,删除新{}并将其replace为string。
 <%: Html.TextBoxFor(x => x.Age,"0") %>