简体   繁体   English

将复杂模型的表单发布到ASP.NET Core MVC中的控制器

[英]Form Post of an Complex Model to Controller in ASP.NET Core MVC

I have a question regarding a Form Post of an complex Model. 我有一个关于复杂模型的表单发布的问题。 My Model has a subclass and IEnumerable s: 我的模型有一个子类和IEnumerable

public class MyViewModel
{
    public int SingleInteger { get; set; }
    public IEnumerable<int> MultipleInts { get; set; }
    public IEnumerable<MySubclass> AssembledClass { get; set; }
    public IEnumerable<string> MultipleStrings { get; set; }
}

public class MySubclass
{
    public int Quantity { get; set; }
    public int Type{ get; set; }
}

What is the best way to get the Input from my View to my Controller? 将输入从视图传输到控制器的最佳方法是什么? Can the Modelbinder even bind this? Modelbinder可以绑定吗?

Can the Modelbinder even bind this? Modelbinder可以绑定吗?

Yes, and it can do a lot more complexed stuff then this class structure. 是的,它可以比此类结构做更多复杂的事情。

What is the best way to get the Input from my View to my Controller? 将输入从视图传输到控制器的最佳方法是什么?

Post is as json. 发布为json。

Example: 例:

You could POST this json 你可以发布这个json

{"singleInteger":1,"multipleInts":[1,2,3],"assembledClass":[{"quantity":1,"type":2}],"multipleStrings":["one","two"]}

To an controller method like this 对于这样的控制器方法

public IActionResult Post([FromBody]MyViewModel model)

And it will be translated into an instance of MyViewModel like this 它将像这样转换为MyViewModel的实例

var model = new MyViewModel
{
    SingleInteger = 1,
    MultipleInts = new List<int>(){ 1,2,3 },
    AssembledClass = new List<MySubclass>{
        new MySubclass 
        {
            Quantity = 1,
            Type = 2
        }
    },
    MultipleStrings = new List<string>(){ "one", "two"} 
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 控制器中带有 FormCollection 模型的 ASP.NET CORE MVC 发布表单 - ASP.NET CORE MVC post form with FormCollection Model in controller 将表单发布到 ASP.NET Core MVC 中的控制器不起作用 - Post form to controller in ASP.NET Core MVC not working Asp.Net Core MVC - 复杂的 Model 未绑定到 Get Controller 操作 - Asp.Net Core MVC - Complex Model not binding on Get Controller action 将复杂的 model 传递给 controller 使用 Z9E0DA8438E1E38A1C30F4B76CE3 Core M34A6659BCEAE779F28185E757ABFCA5Z - Passing a complex model to controller using AJAX in ASP.NET Core MVC Asp.net Core MVC-在控制器动作中的窗体上发布到控制器IEnumerable模型为空 - Asp.net Core MVC - on form posting to controller IEnumerable model in controller action is empty ASP.NET MVC如何发布复杂模型 - ASP.NET MVC How to post complex model ASP.Net MVC 5将表格发布的初始模型参数传递给控制器 - ASP.Net MVC 5 Pass Initial Model Parameter at Form Post to Controller ASP.NET Core MVC 使用 ajax 将模型发布到控制器 - ASP.NET Core MVC posting a model to controller using ajax 全局 model controller ASP.NET Core MVC 6 - Global model in controller ASP.NET Core MVC 6 将文件和模型发布到ASP.NET Core MVC6中的控制器 - Posting files and model to controller in ASP.NET Core MVC6
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM