ASP.Net MVC 3.0 Ajax.BeginForm is redirecting to a Page?

HaBo picture HaBo · Nov 25, 2011 · Viewed 9.3k times · Source

In ASP.Net MVC 3.0 i am using a Ajax.Beginform

and hitting a JsonResult on success of the form i am calling a jQuery Function. but for some reason my form is redirecting to JsonAction

my View


@using (Ajax.BeginForm("ActionName", "Controller", null, new AjaxOptions
           {
               HttpMethod = "POST",
               OnSuccess = "ShowResult"
           }, new { id = "myform" }))
{
    // All form Fields
    <input type="submit" value="Continue" class="button standard" />
}

My controller


public JsonResult ActionName(FormCollection collection)
{
    return Json(new { _status },JsonRequestBehavior.AllowGet);
}

jQuery


<script type="text/javascript">
function ShowResult(data) {
   // alert("I am at ShowResult");
    if (data.isRedirect) {
        window.location.href = json.redirectUrl;
    }
}

for some reason, when i click submit. it runs the JSonResult and redirects the page to host/controller/actionname I have included my

<script src="@Url.Content("jquery.unobtrusive-ajax.min.js")"></script>

in my layout.cshtml

can any one tell me what could be wrong?

I found the problem. Now i have to find the solution on submit I am validating my form

$("#myform").validate({
    submitHandler: function (form) {
   // my logic goes here....
 }});

If i exclude the validation Ajax form works as expected. But if i validate my form then ajax form is not working as expected Thanks

Answer

Adam Tuliper - MSFT picture Adam Tuliper - MSFT · Nov 25, 2011

when this happens its almost always because your script files aren't loaded

note from:

http://completedevelopment.blogspot.com/2011/02/unobstrusive-javascript-in-mvc-3-helps.html

  1. Set the mentioned flag in the web.config:
    1. Include a reference to the jQuery library ~/Scripts/jquery-1.4.4.js
    2. Include a reference to the library that hooks this magic at ~/Scripts/jquery.unobtrusive-ajax.js

So load up fiddler http://fiddler2.com and see if the scripts are being called and loaded.