views:

129

answers:

3

Hi there,

I have some JQuery that uses Ajax to send information back to my controler 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

+2  A: 

You can try to use such syntax with jQuery

$.post(link, {param1: param1, param2: param2 });
Sly
A: 

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.

+3  A: 

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);
statenjason
This works nicely too - http://www.bram.us/2008/10/27/jqueryserializeanything-serialize-anything-and-not-just-forms/
Arnis L.
Interesting. I'll keep that in mind.
statenjason