Skip to main content
 首页 » 编程设计

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

2024年08月06日43tintown

以下是我的相关代码。我想将 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 传递各种对象。希望能帮助到你。