Is it possible to have a strongly typed validation message in a ViewModel?
This works: @Html.ValidationMessage("Name")
Problem Is it possible to get strongly typed helper working?: @Html.ValidationMessageFor(model => model.EventInVM.Name)
ViewModel:
public class EventViewModel
{
public Event EventInVM { get; set; }
public IList<Series> ListOfSeries { get; set; }
}
Controller:
[HttpPost]
public ActionResult Create(EventViewModel eventViewModel)
{
if (!ModelState.IsValid)
{
SetupDropDownsStronglyTyped(eventViewModel);
return View(eventViewModel);
}
uow.Add(eventViewModel.EventInVM);
uow.SaveChanges();
return RedirectToAction("Index");
}
View
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(false)
<fieldset>
<legend>Event</legend>
@Html.Partial("_CreateOrEdit", Model)
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Partial
@model dave开发者_运维问答.Controllers.EventViewModel
<div class="editor-label">
@Html.LabelFor(model => model.EventInVM.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.EventInVM.Name)
@Html.ValidationMessageFor(model => model.EventInVM.Name)
</div>
See this answer here: implementing ValidationMessageFor I believe its because you are referencing another property off of a property.
Instead of @Html.Partial("_CreateOrEdit", Model)
use @Html.EditorForModel()
:
@using (Html.BeginForm()) {
@Html.ValidationSummary(false)
<fieldset>
<legend>Event</legend>
@Html.EditorForModel()
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
and then put the editor template inside ~/Views/Shared/EditorTemplates/EventViewModel.cshtml
精彩评论