我在网上搜索了整个,但没有找到以下问题的解决方案:
假设我有三个视图模型类
public class ViewModelNewPerson
{
public string PersonName;
public string Address;
public string EyeColor;
//etc
}
public class ViewModelSelectPerson
{
public int SelectedPersonId;
}
public class ViewModelComposite
{
public ViewModelSelectPerson selectViewModel;
public ViewModelNewPerson newPersonViewModel;
}
我想做以下事情:
在Controller
中,我想创建一个使用类ViewModelComposite
作为其 Get 模型的GET
Action
,在视图中,我希望用户从以下两个可用操作中进行选择:选择现有人员,以及添加新人员作为所选值。
所以我需要在View
中创建两个表单,并且使用类ViewModelNewPerson
和ViewModelSelectPerson
的 Post 模型将有两个POST
Action
添加到Controller
中。
我的问题是,如何使用自定义模型绑定器进行手动模型绑定,该绑定程序可以在创建新人员Action
将ViewModelComposite
的复合类转换为ViewModelNewPerson
,并在选择现有人员Action
ViewModelSelectPerson
?
编辑:
现在我有一个想法,即分解类ViewModelComposite
并将两个类中的每个属性声明到复合类中,我认为默认模型绑定器可以解决问题。但这会放弃复合模式,这不是我想要的。
您将在窗体中使用一个单一视图模型,您将有一个接收您的单一视图模型的发布操作。
在控制器代码中:
public ActionResult GetSomeData(MyCustomViewModel model){
// add the first element
var person = Person.Add(model.Person);
// update the second object in model, with related / needed ID
model.PersonContent.PersonId = person.id;
// add in related content
var AddedContent = PersonContent.Add(model.PersonContent);
}
单个窗体、多个操作、多个表