Adam
Adam

Reputation: 1715

In MVC, how to determine if partial view response was valid (on the client side)?

I am new to MVC, so hopefully my question will be straight forward. I am thinking of a scenario where the user submits a form (that is a partial view) and it undergoes server validation. I am wondering how I will know the result of the validation on the client side (javascript) after the form is submitted. For example, if validation fails I will obviously want to return the partial view again with validation messages set, but if it passes validation I may not necessarily want to return the partial view. I may want to return a json object with a message or hide a div or something. I want to be able to determine the validation result on the client. Is something like that possible? Or can I approach this a different way?

Upvotes: 4

Views: 2910

Answers (3)

Ahilan
Ahilan

Reputation: 21

Partial views would not have a Layout page. You may use this code to check if the view is rendered as partial view.

@if (String.IsNullOrWhiteSpace(Layout))
{
  // Do somthing if it is partial view
}
else
{
     // Do somthing if it is full page view
}

Upvotes: 2

StriplingWarrior
StriplingWarrior

Reputation: 156524

The tricky part with AJAX is that the client and server both have to agree on what's supposed to come back from the server in any circumstance. You have a few options:

  1. Your server will always return HTML, and jQuery will always replace the editor content with the HTML that comes back. If the model is invalid, you return a PartialView result. If the model is valid, you return a <script> tag that tells the page what it needs to do (e.g. close a dialog, redirect to a different page, whatever). jQuery will automatically run any script it finds in the results when it tries to insert them into the DOM.
  2. Your server will always return a JSON object representing what happened. In this scenario, your client-side javascript code has to be complex enough to take the results and modify your page to match. Under normal circumstances, this will mean that you don't get to take advantage of MVC's validation features.
  3. Same as 2, except that you use a custom utility method to render the partial view you want into a string, and you make that entire string part of the JSON that comes back. The javascript code then just has to be smart enough to check whether the JSON shows a valid or invalid result, and if the result is valid, replace the contents of your editor area with the partialview HTML that is returned as part of the JSON object you got back.
  4. Same as 3, except you develop an event-based architecture where all your AJAX requests will always expect to get back a JSON object with one or more "events" in it. The AJAX code can then be consolidated into one method that hands the events off to an Event Bus. The event bus then passes the event information into callbacks that have "subscribed" to these events. That way, depending on what kind of events you return from the server, you can have different actions occur on the client side. This strategy requires a lot more up-front work to put in place, but once it's done you can have a lot more flexibility, and the client-side code becomes vastly more maintainable.

Upvotes: 4

Erik Philips
Erik Philips

Reputation: 54628

If you are using the MVC Data Annotations for validating your Model, then the controller will have a property called ModelState (typeof(ModelStateDictionary) which as a property of IsValid to determine if your Model passed into the Controller/Action is valid.

With IsValid you can return a Json object that can tell your Javascript what to do next.

Update

Here is a really basic example (USES jQuery):

[SomeController.cs]
public class SomeController : Controller
{
    public ActionResult ShowForm()
    {
        return View();
    }
    public ActionResult ValidateForm(MyFormModel FormModel)
    {
        FormValidationResults result = new FormValidationResults();
        result.IsValid = ModelState.IsValid;
        if (result.IsValid)
        {
            result.RedirectToUrl = "/Controller/Action";
        }
        this.Json(result);
    }
}

[FormValidationResult.cs]
public class FormValidationResults
{
    public bool IsValid { get; set; }
    public string RedirectToUrl { get; set; }
}

[View.js]
$(document).ready(function()
{
    $("#button").click(function()
    {
        var form = $("#myForm");
        $.ajax(
        {
            url: '/Some/ValidateForm',
            type: 'POST',
            data: form.serialize(),
            success: function(jsonResult)
            {
                if (jsonResult.IsValid)
                {
                    window.location = jsonResult.RedirectToUrl;
                }
            }
        });
    });
});

Upvotes: 0

Related Questions