Skip to content Skip to sidebar Skip to footer

Asp.net Mvc Json Open Dialog Box Problem

function postForm() { $.ajax({ type: 'POST', data: $('#myForm').serialize(), dataType: 'json', url: '<%= Url.Action('JSONRequest','Home') %&g

Solution 1:

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

<inputtype="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")  
    <inputtype="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.

Solution 2:

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

<inputtype="submit" onclick="postForm" />  

with

<inputtype="button" onclick="postForm" />  

Post a Comment for "Asp.net Mvc Json Open Dialog Box Problem"