In the controller, I can perform a database search, etc. and add the error message associated with the model property:
public ActionResult CreateJob(CreateJobModel viewModel) { var call = FindCall(viewModel.CallNumber); if (call == null) { ModelState.AddModelError("CallNumber", "Idiot User!"); } }
I do not like that CallNumber is a string, ideally it should refer directly to viewModel.CallNumber, and if I change the name of this property, it should also be changed.
How can I achieve this?
I would suggest that the code end with something like this, which will lead to an expression for accessing the properties:
AddModelFieldError(() => viewModel.CallNumber, "Idiot User!");
But I'm not sure how to create such a method, or in case it is a sub / internal property that needs an error message.
source share