Bind formValue for a property with a different name, ASP.NET MVC

I was wondering if there is a way to bind form values ​​passed to the controller that have different identifiers from the class properties.

The form is sent to the controller with Person as a parameter that has the name of the property, but in the text field of the actual form there is the identifier PersonName instead of Name.

How can I relate this correctly?

+3
source share
2 answers

Don't worry about it, just write a class PersonViewModelthat reflects the 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();
}
+3
source

.

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();
}
+3

Source: https://habr.com/ru/post/1720911/


All Articles