5

As I am working on Asp.Net MVC Application, in my application I am using jQuery.POST method to submit a form.

e.g.

jQuery.post('/Product/Save', jQuery(document.forms[0]).serialize(), 
       function (data) { alert('Product Added Successfully.); }
);

In above code snippet, I want to pass another parameter.. let's say.. ProductID.

So, the idea is, I want to pass both jQuery(document.forms[0]).serialize() and ProductID variable in jQuery.POST method, so I can get both Form and ProductID in my controller's action method.

Could anybody please let me know that I would I do this?

Thanks in Advance.

nunu
  • 3,184
  • 10
  • 43
  • 58

3 Answers3

13

You could use the following plugin to serialize the form into a JSON object and add another parameters:

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

like this:

var data = $('form').serializeObject();
data['ProductId'] = '123';
$.post('<%= Url.Action("Save", "Product") %>', data, function (data) { 
    alert('Product Added Successfully.'); 
});
Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

What about using the Url.Action method to build your calling URL? You can include the additional data you need that way.

<%: Url.Action('Save', 'Product', new { "ProductID", your product id }) %>

This would replace the hard-coded URL in your jQuery.post method call.

Jeff Siver
  • 7,434
  • 30
  • 32
0

How about:

 var url = '<%= Html.BuildUrlFromExpression<MyController>(c => c.Save(":productId")) %>';

You could later replace the url with the actual value in your post URL.

 url.replace(':productId', $productId);
WorldIsRound
  • 1,544
  • 10
  • 15