【发布时间】:2011-05-21 11:49:15
【问题描述】:
我的模型包含一个名为Title 的属性,在我的Create 视图中,我使用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")
}
}
【问题讨论】:
-
仅供参考:同样的“过度激进”绑定发生在 DisplayFor 中。
-
什么是
View.Title?你的意思是ViewBag.Title?您使用的是哪个版本的 ASP.NET MVC?哪个视图引擎? -
是的,这是关于 ViewBag.Title 的,看起来像是绑定到这个变量的编辑器。
-
您能否发布一个允许重现该问题的示例代码。我无法重现它。
EditorFor总是使用模型的属性。 -
不,这不是关于 EditorFor(),这是关于 Html.Editor(string) 方法。我用它来生成表单,模型属性名称(“Title”)作为参数传递,同名的值应该在 ViewBag 中定义。
标签: asp.net-mvc razor model conflict