【问题标题】:How to set default value for @Html.EditorFor(model => model.location)?如何为@Html.EditorFor(model => model.location) 设置默认值?
【发布时间】:2011-10-08 08:06:55
【问题描述】:
我尝试添加 , new { @Value = "test" } 但失败了。
然后我将模型修改为
private string _location = string.Empty;
public string location { get { return _location; } set { _location = value; } }
甚至将 string.empty 更改为我的默认文本,仍然失败。
有什么想法吗?谢谢
【问题讨论】:
标签:
asp.net-mvc-3
html
model
default-value
【解决方案1】:
您的解决方案很好,应该可以。但因为它没有,我认为你正在将空模型传递给你的视图 - 在这种情况下,它永远不会评估位置,它的空值。尝试将非空模型传递给您的视图。
return View(new LocationViewModel());
【解决方案2】:
使用以下来源尝试了您的解决方案,对我来说效果很好。
型号
public class LocationViewModel
{
private string _location = "test";
public string Location
{
get { return _location; }
set { _location = value; }
}
}
动作
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(new LocationViewModel());
}
查看
@model LocationViewModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Test</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Location)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Location)
@Html.ValidationMessageFor(model => model.Location)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>