我的模型包含一个名为Title
的属性,在Create
View 中,我使用ViewBag.Title
设置页面标题。
这就产生了以下问题:Html.Editor
生成的表单将显示ViewBag.Title
中的文本,而不是模型的Title
值。
我发现的唯一解决方法是先调用Html.Editor
,然后设置View.Title
。
有谁有更好的解决方案?
编辑1:我正在使用MVC 3。
编辑2:这是我的DisplayTemplates/Object.cshtml
:
@model dynamic
@using Iconum.VS10CS040.Library.Web.MVC3.Helpers
@if (ViewData.TemplateInfo.TemplateDepth > 1) {
<span class="editor-object simple">@ViewData.ModelMetadata.SimpleDisplayText</span>
} else {
foreach (var prop in ViewData.ModelMetadata.Properties.Where(
pm =>
pm.ShowForEdit
&& !ViewData.TemplateInfo.Visited(pm)
&& pm.ModelType != typeof(System.Data.EntityState)
&& !pm.IsComplexType
)
)
{
if (prop.HideSurroundingHtml) {
<text>@Html.Editor(prop.PropertyName)</text>
} else {
string css = "";
if (prop.Model != null && prop.Model.GetType() != null)
{
css += " " + prop.Model.GetType().ToString().ToLower().Replace('.', '-');
}
if (prop.DataTypeName != null)
{
css += " " + prop.DataTypeName.ToLower();
}
if (prop.IsRequired && prop.ModelType.FullName != "System.Boolean")
{
css += " required";
}
<div class="editor-container @css">
<div class="editor-label">
@if (!String.IsNullOrEmpty(Html.Label(prop.PropertyName).ToHtmlString()))
{
// Use LabelWithForThatMatchesTheIdOfTheInput instead of Label because of a bug (fixed in MVC 3)
@Html.LabelWithForThatMatchesTheIdOfTheInput(prop.PropertyName)
}
@if (prop.IsRequired && prop.ModelType.FullName != "System.Boolean")
{
@Html.Raw(" <span class=\"required\">*<span>");
}
</div>
<div class="editor-field">
@* This the line that causes my problem *@
@Html.Editor(prop.PropertyName)
@Html.ValidationMessage(prop.PropertyName)
</div>
</div>
}
} //foreach
// Loop though all items in the Model with an TemplateHint (UIHint)
foreach (var prop in ViewData.ModelMetadata.Properties.Where(
pm => pm.ShowForEdit
&& !ViewData.TemplateInfo.Visited(pm)
&& pm.ModelType != typeof(System.Data.EntityState)
&& !pm.IsComplexType
&& pm.TemplateHint != null
&& (
pm.TemplateHint == "jWYSIWYG0093"
||
pm.TemplateHint == "jQueryUIDatepicker"
||
pm.TemplateHint == "CKEditor"
)
)
)
{
// TODO: check for duplicate js file includes
@Html.Editor(prop.PropertyName, prop.TemplateHint + "-Script")
}
}
最佳答案
我建议使用EditorFor
而不是Editor
。
Html.EditorFor(x => x.Title)
代替:
Html.Editor("Title")
这样,不仅 View 可以利用您的 View 模型,而且在这种情况下也可以按预期运行。
ASP.NET MVC 3.0 RTM(Razor)的示例:
模型:
public class MyViewModel
{
public string Title { get; set; }
}
Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "ViewBag title";
ViewData["Title"] = "ViewData title";
var model = new MyViewModel
{
Title = "Model title"
};
return View(model);
}
}
看法:
@model AppName.Models.MyViewModel
@{
ViewBag.Title = "Home Page";
}
@Html.EditorFor(x => x.Title)
@{
ViewBag.Title = "Some other title";
}
因此,无论我们在此处尝试滥用多少,编辑器模板都使用正确的模型标题(如果使用
Html.Editor("Title")
则不是这种情况)。关于asp.net-mvc - 在模型中名为Title的属性与View.Title(在MVC中)之间的绑定(bind)冲突,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4375323/