-1

I have a ViewModel that I want to autobind to another ViewModel on post.

Eg. if I have

public class ViewModelA{
    public string Stuff {get;set;}
}

public class ViewModelB{
    public string MyStuff {get;set;}
    .
    .
    .
}

For display/rendering purposes, I want the partial to bind to ViewModelA, because it's a much simpler object and hence it'll hopefully be much more reusable since creating an interactive view is a costly proposition.

However, I need all the form information on the page on post. I suppose I could widen the controller action to take both ViewModelA and ViewModelB, and then do additional logic to assign ViewModelA property into ViewModelB, but is there a cleaner, more declarative way to do this?

I guess I'm wondering if I could tag ViewModelA, with some attribute like this:

 [Bind(Prefix = "ViewModelB", Include = "MyStuff")]

I know I can do it at the action level, but can I inject this logic at the ViewModel level?

Also would be nice if Razor follows a more CQRS approach. eg.

Html.TextBoxFor(target => target.Property, model => model.Property2)

So that on render, the textbox is initialized with Property2 value, but on post, it's posted to target.Property.

4

3 回答 3

0

如果您的两个模型出于绑定目的而具有相同的属性名称,那么无论您是通过继承还是通过具有其业务是设置真实属性名称的辅助属性来实现这一点,这将更加直接。

这将使 ViewModelB 期望能够以不同的方式处理某些属性名称并使视图模板不那么混乱更加清楚。

于 2012-04-27T17:24:24.193 回答
0

只需将其指定ViewModelB为处理表单帖子的操作的参数。

例如:

[HttpPost]
public ActionResult Create(ViewModelB newWidget) {
    // handle creation of widget... all information on the form pertaining to viewmodelB will be
    // available in newWidget
}

使用什么模型来生成视图并不重要;只要有与 ViewModelB 中的属性名称匹配的表单字段名称,Model Binder 就会为您处理它。

于 2012-04-27T17:25:12.507 回答
0

不能继承ViewModelBViewModelA

public class ViewModelA : ViewModelB
{
     public string Stuff {get;set;}
     // etc.
}  

public class ViewModelB
{     
    public string MyStuff {get;set;}
    // etc.
} 

然后在您的 Controller 方法中,只需指定更宽ViewModelB的值,模型绑定仍应映射所有内容。

[HttpPost]
public ActionResult(ViewModelB model)
{
    // etc.
}
于 2012-04-27T17:21:05.473 回答