简体   繁体   中英

Custom validation error message doesn't display in Html.ValidationSummary

I've created a custom validation attribute to apply to my view model. In my form, I have a @Html.ValidationSummary control. When my custom validation attribute is invalid, the summary control doesn't display the error message for some reason.

Here's my custom validator:

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

Here's my view model, with my custom validator attribute applied:

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

Here's my partial view:

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

Here's the method my form is posting to:

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

    return Json("error");  
}

The ModelState.IsValid attribute returns false, so it recognizes my custom validator. But the summary control doesn't automatically display my message. The summary does recognize the Required data annotation validator, and displays the error message.

How can I get the Validation Summary to display my custom error message?

You are returning a JsonResult object with just a string "error" inside, how is MVC able to know what validation message to show on the client-side? If you use normal posting (with ActionResult ) you can just return the same model and the validation messages will appear:

return View(viewModel);

You can also validate the object yourself in the controller and return an error message through the JsonResult class by using return Json("error message here");

Or you could try to get the validation error messages from the ModelState property and return them with Json. Check out the second answer of this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM