I am trying to update a model using jQuery AJAX by passing a JSON to my controller action.
I can see that the values are getting to my controller but some of my model properties like BackgrounColor and BackgroundImage is not updating. Why am I missing here.
public PartialViewResult Edit(Header header)
{
// Get the record from the database
Header oHeader = CreateHeaderObj(header);
Header dbHeader = _headerRepo.GetHeader(header.Id);
// Set the properties from the form
// Todo : Needs better mapping
dbHeader.Title = oHeader.Title;
dbHeader.TitleImage = oHeader.TitleImage;
dbHeader.BackgroundColor = oHeader.BackgroundColor;
dbHeader.BackgroundImage = oHeader.BackgroundImage;
dbHeader.ImageBackDefault = oHeader.ImageBackDefault;
dbHeader.ImageBackClick = oHeader.ImageBackClick;
dbHeader.ImageHomeDefault = oHeader.ImageHomeDefault;
dbHeader.ImageHomeClick = oHeader.ImageHomeClick;
dbHeader.Mode = oHeader.Mode;
// Check if model properties are valid
if (ModelState.IsValid)
{
// Model state is valid, proceed with update
UpdateModel(dbHeader);
_headerRepo.Save();
return PartialView("_Display", dbHeader);
}
else
{
throw new Exception("Failed to update record.");
}
}
Regards,
Ryan
EDIT :
The function CreateHeaderObj returns a Header model with modified values like if the background is a valid hex, then prepend background-color: #. I can see that my backgroundcolor property is getting updated from #f9f9f9 to background-color: #f9f9f9 but it’s not getting saved into the database. All I get is f9f9f9
If you intend to change some values from your view model inside a POST controller action you will need to remove them from the ModelState first. Because HTML helpers first look at modelstate when binding their values and then in the model.
And you should do this for each property that has a corresponding input field and for which you modify the original value that the user entered: