MVC and JQuery: Best practice for retrieving form data
I have some JQuery that uses Ajax to send information back to my controller to be processed
I am doing it like this:
//Define my controls
<%=Html.TextBox("PName", Model.PName, new { id = "pName" })%> ...
....
....
//Get the values from my controls
var param1= $("#pName").val();
....
....
//Define the return URL. Is this how to send info back?
var url = '<%= Url.Content("~/Port/SaveRowAjax") %>/?ID=' + id
+ "&par开发者_开发技巧am1=" + param1
+ "¶m2=" + param2
+ "¶m3=" + param3
+ "¶m4=" + param4
+ "¶m5=" + param5;
$.ajax({
url: url,
success: function(html) {
alert("Success!");
},
});
//My c# code, that processes the request
public void SaveRowAjax(string param1 ....)
{
...
}
Is this the best way of doing it with MVC?
It seems a bit messy when i am contructing the URL to post back to the serverTry using SerializeArray for submitting your form items. It'll box all their values into a JSON object.
var link = "/Port/SaveRowAjax";
var formData = $(":input").serializeArray();
$.post(link,formData);
You can try to use such syntax with jQuery
$.post(link, {param1: param1, param2: param2 });
The way that works for me is this:
jQuery.ajax({
url: '@Url.Action("SaveRowAjax", "Port")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ param1: param1, param2: param2, param3: param3 }),
success: function (result) { }
});
Theres a few ways to do this. I prefer the method outlined here:
http://weblogs.asp.net/mikebosch/archive/2008/02/15/asp-net-mvc-submitting-ajax-form-with-jquery.aspx
Yes, it is based on an older version of MVC but the real beef of the technique is the use of jQuery (which hasnt changed).
One limitation of the technique is that it wont work with file uploads, however, there is a jQuery plugin for doing ajax form posts that does support file uploads (I think through a hidden iframe).
edit: I think the best reason to use this technique is that if the user has javascript disabled, the form will still work.
精彩评论