loveforfire33
loveforfire33

Reputation: 1118

Struggling With Conditional Validation MVC 3

been trying to fix this for a few days now and just cant get it to work!

i have a radio button list which determines the output of a form - one of the radio buttons is to download X amount of files. this radio button has a text box for the user to enter the amount (X) they wish to download.

i only need this textbox to validate if the radio button that corresponds to it is selected - this is what i have so far but cannot get it to work. any help would be appriciated.

MODEL

public class myClass

{
       [Required(ErrorMessage = "Please select the type of output you wish to generate")]
       public int providerType { set; get; }


       public int? numOutput { set; get; }


       public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
       {
           if (providerType == 2 && numOutput == null)
               yield return new ValidationResult("Description must be supplied.");
       }

}

CONTROLLER

    [AcceptVerbs(HttpVerbs.Post)]
    [HttpPost, ValidateInput(false)]
    public ActionResult Spin(myClass theData)

    {

        int? ProviderType = Convert.ToInt16(Request.Form["providerType"]);

        if (ModelState.IsValid)
        {

            //other random processing

        }

    }

VIEW

   <ul>
<li>
  <%=Html.RadioButton("ProviderType","1")%><label>Output A Single Article (With Visible HTML Tags)</label>
 </li>
 <li>
  <%=Html.RadioButton("ProviderType","4")%><label>Output A Single Article (With HTML Pre Rendered - Not Recommended For Articles With Videos)</label>
 </li>
  <li>
  <%=Html.RadioButton("ProviderType", "3")%><label>Output For Mass Submission</label> 
  </li>

 <li>
  <%=Html.RadioButton("ProviderType", "2")%><label>Download Several Copies Of Article (With Visible HTML Tags)</label>
 How Many Artilces (Max 20) 

            <%= Html.TextBoxFor(Model => Model.numOutput)%>
             <%= Html.ValidationMessageFor(Model => Model.numOutput)%>

im still new to MVC so im probably doing something stupid here - any help is much appriciated. The error im getting is that when i select the radio button and dont enter anything in the textbox "Input string was not in a correct format." so obviously the validation is not firing - cant quite figure out why.

Upvotes: 0

Views: 391

Answers (1)

Aadil
Aadil

Reputation: 71

The reason why its not hitting Validation is because your model is not implementing IValidatable Object.

  e.g. public class MyClass:IValidatableObject

Let me know if that works for you. I was able to get the above code working locally and can send you the code if it still doesnt work for you.

Upvotes: 2

Related Questions