Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
                + "&param1=" + 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

like image 593
Alex Avatar asked Oct 07 '09 05:10

Alex


2 Answers

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);
like image 116
statenjason Avatar answered Sep 19 '22 10:09

statenjason


You can try to use such syntax with jQuery

$.post(link, {param1: param1, param2: param2 });
like image 28
Sly Avatar answered Sep 17 '22 10:09

Sly