1

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.

1 Answer 1

1

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

if i have added model level errors in controller by saying addmodel errors then i have to return model to the view with display the model errors. can we do that by have return type javascriptresult. Thanks in advance.
@NetDev - No since the only method for JavScriptResult is this protected internal virtual JavaScriptResult JavaScript(string script); which does not take a model as a parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.