ASP.NET MVC Html.RadioButton Exception

后端 未结 5 1511
梦毁少年i
梦毁少年i 2021-02-19 01:23

I haver a simple radio button list on my page that I render with the following in my view:


<%=         


        
5条回答
  •  自闭症患者
    2021-02-19 02:04

    I just tried something that makes this work. The problem does not occur if I do not do the validation step but of course I need the validation. That gave me a clue for the solution.

    The ValidationMessage HtmlHelper method takes a string argument that is the name of the property or model object being validated. I just changed that name to be "gender2" as follows:

    
    <%= Html.RadioButton("gender", 1) %> Male
    <%= Html.RadioButton("gender", 2) %> Female
    <%= Html.ValidationMessage("gender2") %>
    

    And I changed the validation code to refer to this new name (even though that property does not exist, it still works):

    if (!gender.HasValue)
        ModelState.AddModelError("gender2", "gender required");
    

    This works as desired.

    I would have thought the other should have worked, but this is a simple workaround and I am documenting that here.

    EDIT: By the way I tried changing the gender property to a string instead of a nullable int, and the same exact problem occurs.

    The work around still seems to be in using a different key name for the Validation Message.

提交回复
热议问题