开发者

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
                + "&param2=" + param2
                + "&param3=" + param3
                + "&param4=" + param4
                + "&param5=" + 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 server


Try 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜