2012-06-06 53 views
1

我想知道,有沒有一種方法可以將模型字段中的驗證對象(讓我們說一個Message實例)傳遞給ModelState(或者通過使用一些其他的東西)實例。爲什麼我問這是,我想區分驗證錯誤消息類型,所以我一次只能在視圖中顯示我想要的消息。 (例如:在唯一驗證消息之前顯示的必需消息。)在驗證中將對象作爲錯誤消息傳遞

我試圖使用自定義創建的Message對象,然後我可以使用它的messageType字段進行區分。但由於驗證只返回字符串消息,所以不能想到一種方法。

回答

2

從模型狀態中讀取消息並根據消息內容確定類型是否正常?如果您爲所有驗證設置了自定義消息,則可以完成此操作。

然後你可以評估每條消息尋找特定的內容並採取行動。例如在Required屬性和Info中放置「Error」一詞。

這裏有一個類,你可以用它來測試

型號


public class EmployeeViewModel { 

    public int ID { get; set; } 

    [Display(Name = "First Name")] 
    [Required(ErrorMessage = "Error")] 
    public string FirstName { get; set; } 

    [Display(Name = "Last Name")] 
    [Required(ErrorMessage = "Error")] 
    public string LastName { get; set; } 

    [Display(Name = "Username")] 
    public string Username { get; set; } 

    [Display(Name = "Email Address")] 
    public string EmailAddress { get; set; } 
} 

控制器


using System.Collections.Generic; 
using System.Linq; 
using System.Web.Mvc; 
using TestApp.Models; 

namespace TestApp.Controllers { 

    public class HomeController : Controller { 

     public ActionResult Index() { 
      return RedirectToAction("Test"); 
     } 

     public ActionResult Test() { 
      var model = new EmployeeViewModel(); 
      return View(model); 
     } 

     [HttpPost] 
     public ActionResult Test(EmployeeViewModel model) { 
      // Force an error on this property - THIS should be the only real error that gets returned back to the view 
      ModelState.AddModelError("", "Error on First Name"); 

      if(model.EmailAddress == null) // Add an INFO message 
       ModelState.AddModelError("", "Email Address Info"); 
      if (model.Username == null) // Add another INFO message 
       ModelState.AddModelError("", "Username Info"); 

      // Get the Real error off the ModelState 
      var errors = GetRealErrors(ModelState); 

      // clear out anything that the ModelState currently has in it's Errors collection 
      foreach (var modelValue in ModelState.Values) { 
       modelValue.Errors.Clear(); 
      } 
      // Add the real errors back on to the ModelState 
      foreach (var realError in errors) { 
       ModelState.AddModelError("", realError.ErrorMessage); 
      } 
      return View(model); 
     } 

     private IEnumerable<ModelError> GetRealErrors(IEnumerable<KeyValuePair<string, ModelState>> modelStateDictionary) { 
      var errorMessages = new List<ModelError>() ; 
      foreach (var keyValuePair in modelStateDictionary.Where(keyValuePair => keyValuePair.Value.Errors.Count > 0)) { 
       errorMessages.AddRange(keyValuePair.Value.Errors.Where(error => !error.ErrorMessage.Contains("Info"))); 
      } 
      return errorMessages; 
     } 
    } 
} 

private IEnumerable<ModelError> GetRealErrors(IEnumerable<KeyValuePair<string, ModelState>> modelStateDictionary) { 
    var errorMessages = new List<ModelError>() ; 
    foreach (var keyValuePair in modelStateDictionary.Where(keyValuePair => keyValuePair.Value.Errors.Count > 0)) { 
     errorMessages.AddRange(keyValuePair.Value.Errors.Where(error => !error.ErrorMessage.Contains("Info"))); 
    } 
    return errorMessages; 
} 

查看


@model TestApp.Models.EmployeeViewModel 

<h2>Test</h2> 

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 
    <fieldset> 
     <legend>EmployeeViewModel</legend> 

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

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

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

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

     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 
+0

我也想過用字符串。但是爲此使用字符串是一個好習慣嗎? – SDK

+0

我認爲你只需要看看你想要達到的目標,並問問自己,如果你正在對付給定的框架或與之對抗。就我個人而言,我更喜歡使用爲特定目的而製作的內置對象,並對其進行修改或擴展以獲得缺少的功能,而不是重新發明輪子。所以問問你自己如何選擇你的方法,與系統一起工作還是反對它。 –

+0

我想要做的是區分一些錯誤消息(我認爲這是非常普遍的情況)。我認爲有一種方法可以將它們作爲消息對象而不是消息字符串傳遞,因此我不希望對字符串進行操作(這並不認爲是正確的做法)。 :) – SDK