Clint B Clint B - 3 months ago 39
ASP.NET (C#) Question

ASP.NET Core Entity Model Automatically Maps to View Model

I'm using ASP.NET Core RTM (Full .NET Framework).

I ran into some unexpected behavior with a controller that accepts an entity model as a parameter and returns a view model. In the controller I create a new instance of the view model and use the entity model to populate it.

[HttpGet]
public IActionResult Create(ActiveDirectoryUser model)
{
ApplicationUserView user;

user = new ApplicationUserView
{
UserName = model.UserName,
Email = model.Email.ToLower(),
FirstName = model.FirstName,
LastName = model.LastName,
Active = true
};

return View(user);
}


With the code above I noticed that the email address is not changed to lower case in the view even though in debug the ApplicationUserView object shows that the email is lowercase.

So I did a test where I used static values for the ApplicationUserView object.

user = new ApplicationUserView
{
UserName = "Test",
Email = "test@test.com",
FirstName = "Test",
LastName = "Test",
Active = true
};


With the code above the view still shows the values that were passed in by the ActiveDirectoryUser model.

I don't understand how the values from the ActiveDirectoryUser model are making it to the view and why I can't override them. I've tried to override them in the constructor as shown above and also tried setting them individually like
user.Email = "test@test.com"
.

How can I pass my ApplicationUserView model to the view without any data from the ActiveDirectoryUser model?

Answer

Try ModelState.Clear(); before you send the model back. The page model is stored in ModelState which takes precedence over your current model. Also i assume that ApplicationUserView is the model that your view is bound to..