Asp.net MVC 复合类自定义模型绑定



我在网上搜索了整个,但没有找到以下问题的解决方案:

假设我有三个视图模型类

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 模型的GETAction,在视图中,我希望用户从以下两个可用操作中进行选择:选择现有人员,以及添加新人员作为所选值。

所以我需要在View中创建两个表单,并且使用类ViewModelNewPersonViewModelSelectPerson的 Post 模型将有两个POSTAction添加到Controller中。

我的问题是,如何使用自定义模型绑定器进行手动模型绑定,该绑定程序可以在创建新人员ActionViewModelComposite的复合类转换为ViewModelNewPerson,并在选择现有人员ActionViewModelSelectPerson

编辑:

现在我有一个想法,即分解类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);
}

单个窗体、多个操作、多个表

最新更新