2013-12-10 52 views
1

我使用MVC 4的EntityFramework 5獲取EntityValidationErrors沒有原因

在這個例子中,我獲得兩個EntityValidationErros後,我儘量節省用簡單的形式參數的新的「聯繫人」對象。

聯繫人的屬性之一就是「地址」,這是被填充上了同樣的觀點(與其他聯繫人的屬性。

當我提交表單,我得到一個全新的聯繫對象,具有完整的地址。屬性附加傷害其 然而,相匹配的形式參數,當我試圖挽救它,我得到EntityValidationError(2確切..)失蹤在我的聯繫人的地址參數的

我的觀點:

<div class="editor-label"> 
    @Html.LabelFor(model => model.Address.City) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Address.City) 
     @Html.ValidationMessageFor(model => model.Address.City) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Address.Street) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Address.Street) 
     @Html.ValidationMessageFor(model => model.Address.Street) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Address.State_province) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Address.State_province) 
     @Html.ValidationMessageFor(model => model.Address.State_province) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Address.Zip_postalCode) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Address.Zip_postalCode) 
     @Html.ValidationMessageFor(model => model.Address.Zip_postalCode) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Address.Country) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Address.Country) 
     @Html.ValidationMessageFor(model => model.Address.Country) 
    </div> 

    <br /> 
    <p> 
     <input type="submit" value="Save" /> 
    </p> 

創建Ac內部聯繫控制器:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create(Contact contact) 
    { 
     try 
     { 
      if (ModelState.IsValid) 
      { 
       TempData["contact"] = contact; 
       unitOfWork.currentClient.Contacts.Add(contact); 
       unitOfWork.Save(); 
       return View("Index"); 
      } 

      return View(contact); 
     } 
     catch (Exception ex) 
     { 
      return View(contact); 
     } 
    } 

任何想法?

+1

請張貼相關的代碼 – Maess

+0

我不能。我是stackOverflow的新手,沒有聲望(這意味着我無法發佈圖片) – user3087881

+0

複製並粘貼它,然後使用代碼標籤將其格式化爲代碼。 – Maess

回答

1

只需從modelstate中獲取錯誤即可。

使用LINQ:

​​

另一種選擇:

public static List<string> GetErrorListFromModelState 
               (ModelStateDictionary modelState) 
{ 
     var query = from state in modelState.Values 
        from error in state.Errors 
        select error.ErrorMessage; 

     var errorList = query.ToList(); 
     return errorList; 
} 

資源:

How to get all Errors from ASP.Net MVC modelState?

相關問題