jQuery.POST – 使用Form.Serialize()传递另一个参数 – Asp.net MVC 3
当我在Asp.Net MVC应用程序上工作时,在我的应用程序中,我使用jQuery.POST
方法提交表单。
例如
jQuery.post('/Product/Save', jQuery(document.forms[0]).serialize(), function (data) { alert('Product Added Successfully.); } );
在上面的代码片段中,我想传递另一个参数..让我们说.. ProductID
。
所以,我的想法是,我想在jQuery.POST method
传递jQuery(document.forms[0]).serialize()
和ProductID variable
,因此我可以在我的controller's action method
获取Form and ProductID
。
有人可以告诉我,我会这样做吗?
提前致谢。
您可以使用以下插件将表单序列化为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.'); });
使用Url.Action方法构建您的调用URL怎么样? 您可以通过这种方式包含所需的其他数据。
<%: Url.Action('Save', 'Product', new { "ProductID", your product id }) %>
这将替换jQuery.post方法调用中的硬编码URL。
怎么样:
var url = '<%= Html.BuildUrlFromExpression(c => c.Save(":productId")) %>';
您可以稍后使用postURL中的实际值替换该url。
url.replace(':productId', $productId);