2013-11-09 63 views
1

我已經創建了自定義驗證屬性以應用於我的視圖模型。在我的表格中,我有一個@Html.ValidationSummary控件。當我的自定義驗證屬性無效時,出於某種原因,彙總控件不顯示錯誤消息。自定義驗證錯誤消息不會顯示在Html.ValidationSummary中

這裏是我的自定義的驗證:

public class UserFolderExistsAttribute : ValidationAttribute 
{ 
    private const string _defaultErrorMessage = 
     "A folder with this name already exists"; 
    private readonly object _typeId = new object(); 

    public UserFolderExistsAttribute(string folderName) : 
     base(_defaultErrorMessage) 
    { 
     FolderName = folderName; 
    } 

    public string FolderName { get; private set; } 
    public override object TypeId { get { return _typeId; } } 

    public override bool IsValid(object value) 
    { 
     return false; // return error message to test for now 
    } 
} 

這裏是我的視圖模型,應用了我的自定義的驗證屬性:

[UserFolderExists("Name")] 
public class UserFolderViewModel 
{ 
    [Required(ErrorMessage = "Name is required")] 
    public string Name { get; set; } 
} 

這裏是我的部分觀點:

@using (Ajax.BeginForm("Create", "Folders", 
    new AjaxOptions { OnSuccess = "OnSuccess" })) 
{ 
    @Html.AntiForgeryToken() 

    @Html.TextBoxFor(m => m.Name, new { placeholder = "Name" }) 

    <p>@Html.ValidationSummary()</p> 

    <p><input type="submit" class="create" value="" /></p> 
} 

這裏的方法我的表單發佈到:

[HttpPost] 
public JsonResult Create(UserFolderViewModel viewModel) 
{ 
    if (ModelState.IsValid) 
    { 
     // do something 
    } 

    return Json("error"); 
} 

ModelState.IsValid屬性返回false,因此它可以識別我的自定義驗證器。但彙總控件不會自動顯示我的消息。摘要確認Required數據註釋驗證程序,並顯示錯誤消息。

如何獲取驗證摘要以顯示我的自定義錯誤消息?

回答

0

你正在返回一個JsonResult對象,裏面只有一個字符串"error",MVC如何能夠知道在客戶端顯示的驗證消息?如果使用普通郵寄(以ActionResult),你只需返回相同的模型和驗證消息就會出現:

return View(viewModel); 

您也可以自己驗證對象控制器,並通過JsonResult類通過返回錯誤信息使用return Json("error message here");

您可以嘗試從ModelState屬性獲取驗證錯誤消息並將它們返回給Json。看看this question的第二個答案。

相關問題