2009-10-23 66 views
3

我想知道是否有方法將綁定的表單值綁定到控制器中,這些控制器具有與類屬性不同的Id。將formValue綁定到不同名稱的屬性,ASP.NET MVC

將表單發佈到具有Person的控制器作爲具有屬性Name的參數,但實際表單文本框具有PersonName而不是Name的標識。

我該如何正確地綁定?

回答

3

不要爲此煩惱,只需編寫一個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(); 
} 
3

您可以擁有您自己的該模型的自定義模型活頁夾。

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(); 
} 
相關問題