2011-01-24 51 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);