我想知道是否有一种方法可以将传递到具有与类属性不同 Id 的 Controller 的表单值绑定(bind)。
表单以 Person 作为具有属性 Name 的参数发送到 Controller ,但实际表单文本框的 ID 为 PersonName 而不是 Name。
如何正确绑定(bind)它?
最佳答案
不要为此烦恼,只需编写一个 PersonViewModel
类来反射(reflect)与您的表单完全相同的结构。然后使用 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();
}
关于asp.net-mvc - 将 formValue 绑定(bind)到不同名称的属性,ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1614452/