Rajesh
Rajesh

Reputation: 2502

Returning JavaScriptResult in mvc problem with model validation

I have a return type for a post method of JavaScriptResult. I want to do model validation for this method with return new JavaScriptResult(){}. How can I do this? Like what should I return if a model level error exist.

Upvotes: 1

Views: 2793

Answers (1)

amurra
amurra

Reputation: 15401

Generally, I would try to avoid using JavaScriptResult as it tends to intermingle UI content with controller content, which tends to go against the whole MVC pattern. If I were doing what you were trying to accomplish I would return a JsonResult back to the client and then execute a block of code based on the result. This way if a model fails validation you could return a JsonResult with a failure result and know on the client that the validation failed. It can be achieved like this:

[HttpPost]
public JsonResult Example(ModelName model)
{
    // Validate 
    if (!ModelState.IsValid)
    {
        return new JsonResult()
        {
            Data = new { success = false },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }

    // No validation errors, do stuff

    return new JsonResult()
    {
        Data = new { success = true },
        JsonRequestBehavior = JsonRequestBehavior.AllowGet
    };

}

Then client code:

$.post('/Example', $('#form').serialize(), function (response) {
    if (response.success) {
        // Success, execute js code here
    } else {
        // Validation errors
    }
}, "json");

However, if you need to go the JavaScriptResult route and a validation error occurs, I would either return nothing or some javascript that would notify the user that the validation failed:

[HttpPost]
public JavaScriptResult Example(ModelName model)
{
    // Validate 
    if (!ModelState.IsValid)
    {
        return new JavaScript("alert("Validation Failed!")");
    }

    // No validation errors, do stuff

    return new JavaScript("js to return here if validation passes");
}

Upvotes: 1

Related Questions