Ste*_*nen 8 javascript ajax asp.net-mvc jquery model-binding
我们正在尝试使用一个Ajax(jQuery)调用向ASP应用程序发送多个表单.
我们使用以下jQuery代码:
var formContainer = {
Form1 : form1.serialize(),
Form2 : form2.serialize()
}
$.ajax({
type: "POST",
url: '@Url.Action("CreateModel", "Controller")',
data: formContainer,
success: function (result) { }
});
Run Code Online (Sandbox Code Playgroud)
在服务器上,我们在Request.Form属性中收到以下内容:
Key : Value
Form1 : All serialized form elements for Form1
Form2 : All serialized form elements for Form2
Run Code Online (Sandbox Code Playgroud)
通常我们使用以下方法,因此ASP自动创建具有正确属性值的对象:
public ActionResult CreateModel(ClassForForm1 obj)
Run Code Online (Sandbox Code Playgroud)
但由于这两种形式是一起发送的,因此模型绑定器无法绑定和构建类.因此,对于此操作,我们希望模型构建器使用Request.Form ["Form1"]中的值.
我们不能使用自定义模型绑定器,因为我们使用extern库(DevExpress,他们在此之上编写了自己的实现).
我们使用MEF框架来添加功能(这些功能在视图中添加为表单).出于这个原因,我们不知道后端会有什么期望.因此编写包装器ViewModel是不可接受的.
处理其他表单数据的功能将在其他模块中进行处理.
欢迎任何解决方案!
提前致谢.
这通常是使用组合视图模型来完成的。否则,您需要手动解析请求参数。这是一个小提琴,展示了如何组合来自多个表单的数据。
$(function() {
$('button').click(function(e) {
var form1 = $('#form1');
var form2 = $('#form2');
$.ajax({
type: "POST",
url: '/echo/html/',
data: form1.serialize()+"&"+form2.serialize(),
success: function (result) {
alert(result);
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
在服务器上,您的视图模型将需要:
public class IndexViewModel {
// properties from form1
public string first { get; set; }
// properties from form2
public string last { get; set; }
}
public class First {
public string first { get; set; }
}
public class Last {
public string last { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
还有你的行动签名:
[HttpPost]
public ActionResult Index(IndexViewModel model) {
var firstModel = (new First()).CloneMatching(model);
var lastModel = (new Last()).CloneMatching(model);
return RedirectToAction("Thanks");
}
Run Code Online (Sandbox Code Playgroud)
有关 CloneMatching 扩展方法,请参阅克隆不同对象的属性的最佳方法。
| 归档时间: |
|
| 查看次数: |
1459 次 |
| 最近记录: |