2011-04-26 49 views
0

這工作:@Html.ValidationMessage("Name")ViewModel中是否有強類型驗證消息?

問題是否有可能獲得強類型的輔助工作?:@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> 
+0

編輯模板,您使用的數據標註爲您驗證?例如,你的'Event'類型'Name'屬性是否有'[Required]'屬性或類似的東西? – ataddeini 2011-04-26 02:45:57

+0

不,我不是。我使用LightSpeed作爲我的ORM和一個自定義EntityModelBinder來流過註釋。我認爲這是工作正常,因爲驗證摘要顯示我期望..已經上傳截圖 – 2011-04-26 02:55:27

+0

行。我猜錯誤沒有正確的鍵被添加到'ModelState.Errors'集合。如果錯誤沒有與屬性名稱匹配的鍵,那麼'Html.ValdiationMessageFor'不會顯示它,但摘要仍然會顯示。 – ataddeini 2011-04-26 03:21:14

回答

0

看到這個答案在這裏: implementing ValidationMessageFor 我相信它,因爲你引用他人財產關的屬性。

+0

謝謝@亞當。是的,這指出了我在上面實施的弱類型助手。我想知道是否有更好的方法。 – 2011-04-29 01:55:06

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

+0

謝謝@Darin - 是的,我喜歡用這個更好。雖然沒有幫助強類型的幫手。 – 2011-04-29 01:54:30