3
我想知道是否有方法将绑定的表单值绑定到控制器中,这些控制器具有与类属性不同的Id。将formValue绑定到不同名称的属性,ASP.NET MVC
将表单发布到具有Person的控制器作为具有属性Name的参数,但实际表单文本框具有PersonName而不是Name的标识。
我该如何正确地绑定?
我想知道是否有方法将绑定的表单值绑定到控制器中,这些控制器具有与类属性不同的Id。将formValue绑定到不同名称的属性,ASP.NET MVC
将表单发布到具有Person的控制器作为具有属性Name的参数,但实际表单文本框具有PersonName而不是Name的标识。
我该如何正确地绑定?
不要为此烦恼,只需编写一个PersonViewModel
类,以反映与您的表单完全相同的结构。然后使用AutoMapper将其转换为Person
。
public class PersonViewModel
{
// Instead of using a static constructor
// a better place to configure mappings
// would be Application_Start in global.asax
static PersonViewModel()
{
Mapper.CreateMap<PersonViewModel, Person>()
.ForMember(
dest => dest.Name,
opt => opt.MapFrom(src => src.PersonName));
}
public string PersonName { get; set; }
}
public ActionResult Index(PersonViewModel personViewModel)
{
Person person = Mapper.Map<PersonViewModel, Person>(personViewModel);
// Do something ...
return View();
}
您可以拥有您自己的该模型的自定义模型活页夹。
public class PersonBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext) {
return new Person { Name =
controllerContext.HttpContext.Request.Form["PersonName"] };
}
}
而且你的行动:
public ActionResult myAction([ModelBinder(typeof(PersonBinder))]Person m) {
return View();
}