开发者

Client-side validation doesn't work in asp.net mvc 1 with "if" condition

I asked this question before, but I decided to be more specific, so maybe somebody could help.

My question is about this particular problem:

In the ASP.NET MVC app. I have a check box, "Food/Bev", which is of a boolean type, and i have a "Select" list on the Form, and I'd like to know how to manage this:

If the check box is checked:

  • A dropdown list "Caterer" becomes a required field.

  • A request cannot be submitted unless the Caterer option is

    selected from the list.

If the check box is not checked:

  • The Caterer dropdown list is not a required field.

And vice virsa.

  • If both fields are empty, then these fields are not required.

In the Model I have this code:

if (string.IsNullOrEmpty(Caterer)
                && (FoodBeverage == true))
                yield return new RuleViolation("Caterer", "Caterer is a required field");

In a View I put this code: For the "select" field "Caterer":

<label for="Caterer">Caterer</label>
                    <% if (Model.Request.Caterer == null && Model.Request.FoodBeverage !=null) %>
                    <select name="Caterer", "required">
               <option>A</option>
               <option>B</option>
               <option>C</option>

For the "checkbox" field "Food/Bev":

<% if (!Model.Request.FoodBeverage && Model.Request.Caterer 开发者_JAVA技巧== null) %>         
                    <%= Html.CheckBox("FoodBeverage", Model.Request.FoodBeverage, new { @class = "required" })%>  
                    <%= Html.ValidationMessage("FoodBeverage", "*")%>

The problem is that the system treats these fields as "required" in both scenarios: if they are both "null" and in the case if one of them is selected or checked.

Looks like the "if" condition on the form doesn't work.


I think the problem here is simply that the If logic isn't validated by the ValidateInput attribute; assuming you're using that of course.

Because MVC1 doesn't do client side validation, this is probably one of the cases where you can implement it, for your very specific requirement.

Add a Javascript Submit function to your form submit, and then you can check the state of the checkbox and that the select list has a valid selection, and simply return false if it's not.

If you check the output code as it stands, you can find the CSS class names the validation logic puts on, so you can emulate the same behavior.

Also, I know this isn't a solution, but if you can upgrade to a later version of MVC I would try it, the unobstrusive ClientSide validation in MVC3 is far superior and anything that can avoid a server round-trip in my book is good.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜