ASP.NET MVC - 表单和模型绑定器中的多个模型

ias*_*ons 6 asp.net-mvc model-binders

我有一个表格需要填充2个模型.通常我在表单post post上使用ModelBinderAttribute,即

    [Authorize]
    [AcceptVerbs("POST")]
    public ActionResult Add([GigBinderAttribute]Gig gig, FormCollection formCollection)
    {
       ///Do stuff
    }
Run Code Online (Sandbox Code Playgroud)

在我的表单中,字段的名称与模型属性相同...

但是在这种情况下,我有2个不同的模型需要填充.

我该怎么做呢?有任何想法吗?可能吗?

ias*_*ons 9

实际上......最好的方法是这样做:

public ActionResult Add([GigBinderAttribute]Gig gig, [FileModelBinderAttribute]File file) {
Run Code Online (Sandbox Code Playgroud)

}

您可以使用多个属性!


Cra*_*ntz 8

在这种情况下,我倾向于使用单一模型类型来包含所涉及的各种模型:

class AddModel
{
     public Gig GigModel {get; set;}
     public OtherType OtherModel {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

......并绑定它.

  • 从MVC 2开始,如果使用EditorFor(model => model.Gig),它会为您提供前缀.您仍然可以将所有子模型作为单独的参数使用,从而允许更容易地细分属性(例如,`ActionResult SomePostAction([Bind(Include = {"list","of","bindable","fields"}, Prefix ="Gig"] GigModel演出,[Bind(...)] OtherModel其他)`).然后你只需要从那里建立一个复合模型:`var m = new AddModel {Gig = gig,OtherType = other }`. (2认同)