关于 MVC 数据注释、编辑器模板和验证的问题
上下文:使用 EF 的 MVC 2 应用程序。
为什么有些有效,但有些无效?显示名称设置为“法院名称”,但没有进行验证,即我没有看到错误消息。我认为编辑器模板会干扰验证,否则 Model.IsValid 不适用于复杂的视图模型。
有什么想法吗?
部分类:
[MetadataType(typeof(CourtMetaData))]
public partial class Court
{
private class CourtMetaData
{
[Required(ErrorMessage = "Court Name is required")]
[DisplayName("Court Name")]
public System.String CourtName
{
get;
set;
}
}
}
控制器:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult New(CourtsNewViewModel court)
{
if (ModelState.IsValid)
{
db.AddCourt(court);
return View("List");
}
else
{
return View("New", court);
}
}
视图模型:
public class CourtsNewViewModel : ViewModelBase
{
public Court Court {get; private set; }
public IEnumerable<CourtType> CourtTypes { get; private set; }
public CourtsNewViewModel()
{
CourtTypes = db.GetAllCourtTypes();
}
}
视图:
Html.EditorFor(model => model.Court.CourtName, "LongString")
编辑器模板:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.String>" %>
<div class="editor-row">
<div class="editor-label">
<%= Html.LabelFor(model => model) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model)%>
<%= Html.ValidationMessageFor(model => model) %>
</div>
</div>
Context: MVC 2 app using EF.
Why does some of this work, but some doesn't? The display name gets set to "Court Name" but no validation is happening, i.e. I don't see the error message. I'm thinking the editor templates are interfering with validation, or else Model.IsValid doesn't work with a complex view model.
Any thoughts?
PARTIAL CLASS:
[MetadataType(typeof(CourtMetaData))]
public partial class Court
{
private class CourtMetaData
{
[Required(ErrorMessage = "Court Name is required")]
[DisplayName("Court Name")]
public System.String CourtName
{
get;
set;
}
}
}
CONTROLLER:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult New(CourtsNewViewModel court)
{
if (ModelState.IsValid)
{
db.AddCourt(court);
return View("List");
}
else
{
return View("New", court);
}
}
VIEW MODEL:
public class CourtsNewViewModel : ViewModelBase
{
public Court Court {get; private set; }
public IEnumerable<CourtType> CourtTypes { get; private set; }
public CourtsNewViewModel()
{
CourtTypes = db.GetAllCourtTypes();
}
}
VIEW:
Html.EditorFor(model => model.Court.CourtName, "LongString")
EDITOR TEMPLATE:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.String>" %>
<div class="editor-row">
<div class="editor-label">
<%= Html.LabelFor(model => model) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model)%>
<%= Html.ValidationMessageFor(model => model) %>
</div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题如下:
court
变量已被使用,因为您的模型上有Court
属性。现在重命名参数:
一切都应该按预期工作。
Here's the gotcha:
The
court
variable is already used as you have aCourt
property on your model.Now rename the parameter:
Everything should work as expected.