I've noticed that one of my ASP.NET MVC apps started generating a NullReferenceException error when a custom error message is added to the model state. When that happens, I end up getting an error on one of the Html.TextBoxFor calls the view uses. The controller looks like this:
public async Task<ActionResult> ConfirmPayment(PaymentInfo model){
try{
//this will generate an exception
PaymentManager.Pay(...);
}
catch(PaymentException ex){
_logger.Error(ex);
var field = MapErrorToField(ex); //this returns the name of one of the fields
ModelState.AddModelError(field, "error");
}
I've found some links that suggested the problem could be solved by calling SetModelValue. Unfortunately, that did not solve my problem.
SOLVED IT
The problem: the view had some code that looked like this:
<div class="form-group @(!ViewData.ModelState.IsValid && ViewData.ModelState[nameof(Model.ReturnTicket)].Errors.Count > 0) ? "has-error" : "")">
...
Now, the thing is ReturnTicket won't be present in all the requests, so there will be times when there's no Model.ReturnTicket in the ModelState dictionary. The solution is simple:
<div class="form-group @((!ViewData.ModelState.IsValid&& ViewData.ModelState.Keys.Contains(nameof(Model.ReturnTicket)) && ViewData.ModelState[nameof(Model.ReturnTicket)].Errors.Count > 0) ? "has-error" : "")">
....
The additional condition solves the error. Unfortunately, the error message pointed to a completely different place (like 10 lines above of where thr problem was...), making it really hard to understand what's going on...
Thanks again.