网站建设小组实训总结,wordpress 精简主题,wordpress数据库访问优化,外贸网站推广 上海从后台组织好数据然后传递到页面倒是水到渠成很方便#xff0c;因为MVC自身就将这样的需求内建到了这个系统中。我只需要在后台组织好一个List 或IEnumerable类型的变量#xff0c;将需要传递的数据模型扔进去便可。 比如这里我们向视图返回5条product信息在页面进行展示因为MVC自身就将这样的需求内建到了这个系统中。我只需要在后台组织好一个List 或IEnumerable类型的变量将需要传递的数据模型扔进去便可。 比如这里我们向视图返回5条product信息在页面进行展示仅仅是返回这么简单。 然后在页面我们就毫不费力地得到了后台传过来的数据模型然后进行显示即可。 但问题是如何又将多个模型传回后台去呢。一个form一般只传递一个模型我们可以在JavaScript里序列化多个模型然后通过ajax 传递回去。 1.首先改造页面假设在页面有很多输入框供用户输入模型的相关信息并且搞一个按扭来提交。 tableforeach (Product item in Model){tr iditem.ProductIDtdinput nameProductName //tdtdinput nameSupplierID //tdtdinput nameCategoryID //td/tr}
/table
button idgoGo/button 2.然后在JavaScript中获取这些输入值最后将所有模型整合到一个models变量中。 var models [];$.each($(table tr), function(i, item) {var ProductName $(item).find([nameProductName]).val();var SupplierID $(item).find([nameSupplierID]).val();var CategoryID $(item).find([nameCategoryID]).val();models.push({ ProductName: ProductName, SupplierID: SupplierID, CategoryID: CategoryID });}); 当然这些是写到按扭的单击事件中的。 所以完整的代码看起来应该是这个样子。 script typetext/javascript$(#go).click(function() {var models [];$.each($(table tr), function(i, item) {var ProductName $(item).find([nameProductName]).val();var SupplierID $(item).find([nameSupplierID]).val();var CategoryID $(item).find([nameCategoryID]).val();models.push({ ProductName: ProductName, SupplierID: SupplierID, CategoryID: CategoryID });});});
/script 到这里我们可以加个debugger测试一下有没有有前台代码中成功获取到输入框的值及组织好的模型对不对。 在页面按F12打开开发者工具然后试着在页面输入一些值最后单击按扭。 我们看到在遍历了所有输入框后以每行为单位当成一个Product模型压入models变量中。这个时候models变量中保存了所有信息。 3.准备后台接收数据的Action 。我们当然是接收多个模型所以接收类型选择为ListProduct public ActionResult ReceiveData(ListProduct products){string result products null ? Failed : Success;return Content(result);} 4.最后一步将models变量通过Ajax传送到后台 这一步是最关键的因为ajax格式没写好后台是无法接收到正确的数据的。经过我颇费心神的研究最后得出的ajax代码大概是下面这个样子的 $.ajax({url: ../../Home/ReceiveData,data: JSON.stringify(models),type: POST,contentType: application/json; charsetutf-8,success: function(msg) {alert(msg);}}); 最后完整的前台代码大概应该是这个样子的。 script typetext/javascript$(function() {$(#go).click(function() {var models [];$.each($(table tr), function(i, item) {var ProductName $(item).find([nameProductName]).val();var SupplierID $(item).find([nameSupplierID]).val();var CategoryID $(item).find([nameCategoryID]).val();models.push({ ProductName: ProductName, SupplierID: SupplierID, CategoryID: CategoryID });});$.ajax({url: ../../Home/ReceiveData,data: JSON.stringify(models),type: POST,contentType: application/json; charsetutf-8,success: function(msg) {alert(msg);}});});})
/script 5.调试看结果 结果显示我们接收到了前台传过来的每一个数据完工。转载于:https://www.cnblogs.com/Wayou/p/pass_multi_modes_to_controller_in_MVC.html