During ModelState.IsValid check, I need to change a property of the model and then return to View. Here is how my method looks like:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SaveProject(MainProjectViewModel model, string id = null)
{
if (string.IsNullOrEmpty(id))
{
if (!ModelState.IsValid)
{
bool validClientCheck = this.CheckIfClientNameAndIdAreValid(model.ProjectModel.ClientName, model.ProjectModel.ClientId);
if (!validClientCheck)
{
ModelState.AddModelError("ProjectModel.ClientId", $"Please select a valid client!");
model.ProjectModel.ClientId = null;
}
return View(model);
}
await this.projectService.SaveProject(model, "create");
}
return RedirectToAction("SaveProject", "Project", new { id = model.ProjectModel.Id });
}
Even that I have model.ProjectModel.ClientId = null;
in the view the hidden field for ClientId is still populated with the client id. How do I change the change the model before returning it to the view?
Model binding in View is not simple when you involve the validation with ModelState
.
For a specific field in post form, you could use a key to access it in the variable ModelState
. If you want to modify the value of that field, you should modify the value in the variable ModelState
instead of the page model
.
In your case, you could add codes as below:
// Add custom error before the model validation...
ModelState.AddModelError("ProjectModel.ClientId", $"Please select a valid client!");
if (!ModelState.IsValid)
{
// Modify the value to empty
ModelState["ProjectModel.ClientId"].RawValue = ""; //add this line after set model error
}
return View(model);