Reputation: 173
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>
Upvotes: 0
Views: 881
Reputation: 1039538
Here's the gotcha:
public ActionResult New(CourtsNewViewModel court)
The court
variable is already used as you have a Court
property on your model.
Now rename the parameter:
public ActionResult New(CourtsNewViewModel courtModel)
Everything should work as expected.
Upvotes: 1