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?
You need to cancel the default form submission by returning
falseinside the buttononclickhandler: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:
And in javascript:
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.