简体   繁体   English

将复杂对象绑定到MVC控制器

[英]Bind complex object to mvc controller

I'm creating an mvc4 application and i have an issue. 我正在创建一个mvc4应用程序,但我遇到了问题。

I have a model class for example: 我有一个模型类,例如:

 public class ModelClass
{
   public ClassA a {get; set;}
   public ClassB b {get; set;}
   public ClassC c {get; set;}
   ...
}

Each of thease classes have their own properties, for example: 每个thease类都有自己的属性,例如:

public class ClassA
{
   public String a1 {get; set;}
   public String a2 {get; set;}
   ...
}

 public class ClassB
{
   public String b1 {get; set;}
   public String b2 {get; set;}
   ...
}

...

I have a view like this: 我有这样的看法:

<input type="text" name="a1" id="a1" />
<input type="text" name="a2" id="a1" />
<input type="text" name="b1" id="a1" />
<input type="text" name="b2" id="a1" />
...

How should my controller or view look so I can bind ModelClass to Controller? 我的控制器或视图的外观如何,以便可以将ModelClass绑定到Controller?

 [HttpPost]
    public ActionResult CreateSomething(ModelClass model)
    {
       //insert code here
    }

Or I have to do a custom model binding? 还是我必须做一个自定义模型绑定?

There's nothing you need to do in your controller. 您无需在控制器中做任何事情。 You simply need to name your inputs properly. 您只需要正确命名输入即可。 Based on your structure. 根据您的结构。 Your fields should look like: 您的字段应如下所示:

<input type="text" name="a.a1" />
<input type="text" name="a.a2" />
<input type="text" name="b.b1" />
<input type="text" name="b.b2" />

It's preferable to just use the HTML helpers as they'll always generate the right names for you. 最好只使用HTML帮助器,因为它们将始终为您生成正确的名称。 For example: 例如:

@Html.TextBoxFor(m => m.a.a1)

There might be some neat solutions out there, but if things get too complicated, you can always fall back on FormCollection . 那里可能有一些简洁的解决方案,但是如果事情变得太复杂了,您总是可以使用FormCollection Your code would then look something like this; 您的代码将如下所示;

[HttpPost]
public ActionResult CreateSomething(FormCollection collection)
{
    var model = new ModelClass();
    model.a = new ClassA();
    model.a.a1 = collection["a1"].ToString();
    model.a.a2 = collection["a2"].ToString();
    //....

    model.b = new ClassB();
    model.b.b1 = collection["b1"].ToString();
    model.b.b2 = collection["b2"].ToString();
    //...
}

In my opinion this is the most controllable solution, though it is not the most elegant. 我认为这是最可控的解决方案,尽管它不是最优雅的解决方案。 It nearly always works. 它几乎总是有效。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM