maztt
maztt

Reputation: 12294

asp.net mvc json open dialog box problem

 function postForm()  

{

 $.ajax({ 

     type: "POST",  

     data: $("#myForm").serialize(),  

     dataType: "json",

     url: '<%= Url.Action("JSONRequest","Home") %>',


     success: function(result)  
     {  
         window.alert(result.name);  
     },                  
     error : function()  
     {  
         window.alert('error');  
     }  
 });  

}

 Html.BeginForm("JSONRequest", "Home", FormMethod.Post, new { id = "myForm" });
 Html.TextBox("mazhar")  
 <input type="submit" onclick="postForm" />  
 Html.EndForm();



 public ActionResult JSONRequest(FormCollection form)
    {

        string a = form["mazhar"];
        var data = new { name = "aaaa", Success = "Record is Succesfully Saved", ErrorMessages = "abc" };
        return Json(data);  
    }

Ok the problem is that the dialog box is opening after running this code which is asking to save file. Can someone tell me how to resolve this issue? Why does this box comes afterall?

Upvotes: 0

Views: 1882

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039140

You need to cancel the default form submission by returning false inside the button onclick handler:

<input type="submit" onclick="postForm(); return false;" />

That being said, I would suggest you a better solution. Use the jquery.form plugin which enables you to ajaxify an HTML form. This way much of the duplication in your code could be simplified:

Html.BeginForm("JSONRequest", "Home", FormMethod.Post, new { id = "myForm" });
    Html.TextBox("mazhar")  
    <input type="submit" value="OK" />  
Html.EndForm();

And in javascript:

$(function() { 
    $('#myForm').ajaxForm({
        success: function(result) {  
            window.alert(result.name);  
        },                  
        error : function() {  
            window.alert('error');  
        }  
    }); 
});

This way you no longer need to specify url, method, manually serialize form fields, etc... You also don't need to pollute your HTML markup with javascript functions. This is unobtrusive javascript. Another advantage of this approach is that now you will be able to externalize this javascript into a separate static .js file as it no longer relies on server side code (<%= Url.Action("JSONRequest","Home") %>) and this you will benefit from reducing the bandwidth and caching static resources.

Upvotes: 1

Amitabh
Amitabh

Reputation: 61257

I think you are posting the form twice. You should use Ajax.BeginForm instead of normal form. And remove the jQuery Ajax call.

Here is a very good example of using Ajax Form.

http://davidhayden.com/blog/dave/archive/2009/05/19/ASPNETMVCAjaxBeginForm.aspx

Or you can also try by replacing

<input type="submit" onclick="postForm" />  

with

<input type="button" onclick="postForm" />  

Upvotes: 1

Related Questions