是否可以在ViewModel中使用强类型验证消息?

时间:2011-04-26 02:41:21

标签: asp.net-mvc-3

这有效:@Html.ValidationMessage("Name")

问题是否可以让强类型助手工作?:@Html.ValidationMessageFor(model => model.EventInVM.Name)

enter image description here

视图模型:

public class EventViewModel
{
    public Event EventInVM { get; set; }
    public IList<Series> ListOfSeries { get; set; }
}

控制器:

 [HttpPost]
    public ActionResult Create(EventViewModel eventViewModel)
    {
        if (!ModelState.IsValid)
        {
            SetupDropDownsStronglyTyped(eventViewModel);
            return View(eventViewModel);
        }

        uow.Add(eventViewModel.EventInVM);
        uow.SaveChanges();
        return RedirectToAction("Index");
    }

查看

   <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>
}

部分

@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>

2 个答案:

答案 0 :(得分:0)

在此处查看此答案: implementing ValidationMessageFor 我相信它是因为你引用了另一个属性。

答案 1 :(得分:0)

而不是@Html.Partial("_CreateOrEdit", Model)使用@Html.EditorForModel()

@using (Html.BeginForm()) {
    @Html.ValidationSummary(false)
    <fieldset>
        <legend>Event</legend>
        @Html.EditorForModel()
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

然后将编辑器模板放在~/Views/Shared/EditorTemplates/EventViewModel.cshtml