9
votes

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

1
Is your javascript callback called? Have you checked with fiddler, that your JSon object is returned correctly to the browser? What do you mean excactly with redirecting to JsonAction?Jan
my java script is in the same page. Because it is redirecting to different page. JavaScript can;t be called. and yes my Json object is returned as expected. i see json result in the new redirected pageHaBo

1 Answers

18
votes

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.