2011-01-24 55 views
5

由于我在处理Asp.Net MVC应用程序,在我的应用程序中,我使用的是jQuery.POST方法来提交表单。jQuery.POST - 通过Form.Serialize()传递另一个参数 - Asp.net MVC 3

例如

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

在上面的代码片段,我想通过另一个参数..让我们说.. ProductID

所以,这个想法是,我想通过在jQuery.POST methodjQuery(document.forms[0]).serialize()和​​,所以我可以在我的controller's action method同时获得Form and ProductID

有没有人请让我知道我会这样做?

在此先感谢。

回答

13

您可以使用following plugin序列化的形式进入一个JSON对象,并添加其他参数:

$.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; 
}; 

这样的:

var data = $('form').serializeObject(); 
data['ProductId'] = '123'; 
$.post('<%= Url.Action("Save", "Product") %>', data, function (data) { 
    alert('Product Added Successfully.'); 
}); 
0

如何使用Url.Action方法来构建您的调用URL?您可以包含您需要的额外数据。

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

这将取代jQuery.post方法调用中的硬编码URL。

0

如何:

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

你以后可以用您的帖子网址中的实际值替换该网址。

url.replace(':productId', $productId);