将 formValue 绑定到不同名称的属性,ASP.NET MVC [英] Bind formValue to property of different name, ASP.NET MVC
本文介绍了将 formValue 绑定到不同名称的属性,ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有办法绑定传递给控制器的表单值,这些值与类属性具有不同的 Id.
I was wondering if there was a way to bind form values passed into a controller that have different Id's from the class properties.
该表单以 Person 作为参数发送到控制器,该控制器具有 Name 属性,但实际表单文本框的 id 为 PersonName 而不是 Name.
The form posts to a controller with Person as a parameter that has a property Name but the actual form textbox has the id of PersonName instead of Name.
如何正确绑定?
推荐答案
不要理会这个,只需编写一个 PersonViewModel
类来反映与您的表单完全相同的结构.然后使用 AutoMapper 将其转换为 Person
.
Don't bother with this, just write a PersonViewModel
class that reflects the exact same structure as your form. Then use AutoMapper to convert it to 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();
}
这篇关于将 formValue 绑定到不同名称的属性,ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文