开发者

ASP.NET MVC: Textboxes don't get highlighted when I access Modelstate.AddModelError Manually

开发者 https://www.devze.com 2023-01-10 19:10 出处:网络
Let\'s say I have this property [Required(ErrorMessage = \"Add this property\")] public string MyProperty {get; set;}

Let's say I have this property

[Required(ErrorMessage = "Add this property")]
public string MyProperty {get; set;}

When I use modelbinding validation like this

UpdateModel(myModel);

Then when there is an error the form is re-displayed, and the textbox representing MyProperty is highlighted (i.e. red borders and pink background). The Html.ValidateMessageFor() display also error message next to the textbox.

But, when I do it manually, like this

if(string.NullOrEmpty(myModel.MyProperty))
  ModelState.AddModelError("MyProperty", "Custom message");

If there's an error, I still get the error message. But only Html.ValidationSummary()) displays list of error on top of the page. But the texbox is not highlighted anymore and the Html.ValidateMessageFor() doesn't display an开发者_开发技巧ything at all.

Is there anything I can do to fix that?

Thanks for helping.


After over 2 days without any answer, I suspected that I didn't ask this question the right way. So, I asked differntly and got an answer. I'll then answer myself this question in case someone have the same problem.

The whole thing was about not prefixing keys when the model is a composite one. For instance, in my case:

public class FormViewModel
{
  public OrganizationData organizationData { get; set; }
}

And OrganizationData is defined by

public class OrganizationData
{
  public string OrganizationName { get; set; }
}

So I should have done this

if(string.NullOrEmpty(formViewModel.organizationData.OrganizationName))
   ModelState.AddModelError("organizationData.OrganizationName", "Name can't be empty")

But, I omitted the prefix organizationData and rather did

ModelState.AddModelError("OrganizationName", "Name can't be empty")

On the view, the Html helper will check the ModelState to know if there is error associate to his key. So, if that's the cae, it highlights itself. In that case, organizationData.OrganizationName and OrganizationName are different. So the textbox doesn't highlight itself.

One more thing. I didn't experience the same with TryUpdateModel() because, not only it uses AddModelError() internally, but also uses an algorithm that can figure out the right key.

I guess I got the lesson. I was able to solve some other pending problem just by knowing this mechanism.

Thanks to Darin Dimitrov and Ian Galloway.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号