views:

145

answers:

1

I have a partial view which has a Ajax.BeginForm, with a UpdateTargetID set. When the validation on the form fails the update target id is replaced with the validation errors, but when there are no validation errors users should be redirected to a new page.

The code in my Partial view is

<div id="div_UID">
    <% using (Ajax.BeginForm("FindChildByUID", new AjaxOptions { UpdateTargetId = "div_UID" } ))
       {%>
            <p>
                <label>UID:</label>
                <%= Html.TextBox("UID") %>
            </p>
            <input type="submit" value="Continue" />
     <% } %>
 </div>
</pre>

The code in my controller is as follows

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult FindChildByUID(Student student)
    {

        Student matchingStudent = _studentService.FindChildByUID(student.UID);
        if (matchingStudent == null)
        {
            ModelState.AddModelError("UID", String.Format("No matching child found for the entered UID: {0}", student.UID));

            return PartialView();

        }
        else
        {
            // full view
            return RedirectToAction("ConfirmChildDetails", matchingStudent);
        }
    }

So, for I have been unsuccessful to display the full view on it's own, as it always seems to dipslay the full view in the UpdateTargetID div specfied in the Ajax.BeginForm.

Any suggestions on how I can get this to work?

Thanks

+1  A: 

What your AJAX post is doing is making a request and waiting on a response that contains html to input onto the page. The configuration is such that whatever html is returned will be injected into the div you've named "div_UID".

I typically avoid scenarios like this and use traditional posting if a redirect is required upon a successful outcome of the POST.

I imagine you could do it like this using jQuery to submit rather than the Ajax.BeginForm (or just set a callback function for your Ajax.BeginForm):

function SubmitForm(form) {
    $(form).ajaxSubmit({ target: "#div_to_update", success: CheckValidity });
}

function CheckValidity(responseText) {
    var value = $("#did_process_succeed").val();

    if (value == "True") {
        window.location.replace("url_of_new_action_here");
    }
}

You just have to have a hidden field in your partial view called "did_process_succeed" and set the value of True or False based on some logic in your controller.

There are likely other ways as well. Perhaps someone else will chime in. I hope this helps for now.

Chris F
Thanks very much for your response. One thing I am not sure is how to pass a value for the responseText parameter from the Controller action. It would be great if you could provide me an example of how to do this.
bhiku