In my action I use a InsertPerson model that has the following properties:
pulbic class InsertPerson
{
[Required]
public string Name{get;set;}
}
and I have a DTO model that is passed to my repository:
public class PersonDto
{
public int Id{get;set;}
public string Name{get;set;}
public string LastName{get;set;}
}
my action:
[HttpPost]
public ActionResult Create(InsertPerson insertPerson)
{
if(ModelState.IsValid){
var personDto = new PersonDto();
UpdateModel(personDto)
//UpdateModel(personDto, "insertPerson") I've tried this too
}
}
why it doesn’t work(after UpdateModel all properties is still null)?
Is there any way to update my personDto using UpdateModel?
I know about AutoMapper but I think it’s boring to use in controller.
My view:
@model Help_Desk.ViewModel.InsertPersonViewModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.InsertPerson.Name)
<button type="submit">Save</button>
}
and my viewmodel:
public class InsertPersonViewModel
{
public InsertPerson InsertPerson{ get; set; }
}
Ok, now we see the problem. The information that was missing is that you were using a View Model, and the View Model creates a “container” of sorts that must be accounted for in the UpdateModel.
What’s happening is that UpdateModel is trying to literally update “InsertPerson.Name” in your personDto object. Since that doesn’t exist, it’s not working.
You can fix this by specifying
UpdateModel(personDto, "InsertPerson")