[英]MVC C# - AJAX Passing 2 Models to Controller
Following is my relevant Code. 以下是我的相关守则。 I want to pass 2 Models to the POST Method.
我想将2个模型传递给POST方法。
How to pass 2 Models to Controller? 如何将2个模型传递给控制器?
var mod1 = [], mod2 = [];
mod1.push({
Server: Server,
Name: Name
});
mod2.push({
POP: POPServer,
....
});
Settings = JSON.stringify({ 'Settings ': mod1 });
jq.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Site/insertSettings',
data: Settings ,
success: function () {
....
}
});
Controller 调节器
[HttpPost]
public JsonResult insertSettings(Settings mod1, OtherSettings mod2)
{
....
}
My approach in this kind of situations is just to create a model that contains both models. 我在这种情况下的方法就是创建一个包含两个模型的模型。 It will be something like this:
它将是这样的:
public class InsertSettingsViewModel()
{
public Settings settings { get; set; }
public OtherSettings otherSettings { get; set; }
}
So your controller is going to receive as a parameter the big object: 因此,您的控制器将作为参数接收大对象:
[HttpPost]
public JsonResult insertSettings(InsertSettingsViewModel model)
{
//Here you manipulate your objects
}
And your JS action is going to provide the object 而你的JS动作将提供对象
var bigMod = [];
var mod1 = [],
var mod2 = [];
mod1.push({
Server: Server,
Name: Name
});
mod2.push({
POP: POPServer,
....
});
bigMod.push({
settings: mod1,
otherSettings : mod2
})
Settings = JSON.stringify({ 'model': bigMod });
This way is a cleaner code, and I really don't think you could pass a controller various objects. 这种方式是一个更干净的代码,我真的不认为你可以传递一个控制器的各种对象。 Hope it helps.
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.