gpt4 book ai didi

c# - MVC C# - AJAX 将 2 个模型传递给 Controller

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:01 25 4
gpt4 key购买 nike

以下是我的相关代码。我想将 2 个模型传递给 POST 方法。

如何将 2 个模型传递给 Controller ​​?

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)
{
....
}

最佳答案

在这种情况下,我的方法是创建一个包含两个模型的模型。它将是这样的:

public class InsertSettingsViewModel()
{
public Settings settings { get; set; }
public OtherSettings otherSettings { get; set; }
}

因此您的 Controller 将接收大对象作为参数:

[HttpPost]
public JsonResult insertSettings(InsertSettingsViewModel model)
{
//Here you manipulate your objects
}

并且您的 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 });

这种方式是一种更简洁的代码,我真的不认为您可以向 Controller 传递各种对象。希望能帮助到你。

关于c# - MVC C# - AJAX 将 2 个模型传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29032003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com