2

I'm new to MVC3. I have problem in custom validation, for example

In my BasicInfoViewModel.cs,

[Required]
    [Display(Name = "State", ResourceType = typeof(Resources.Global))]
    public string State { get; set; }

    [Display(Name = "City", ResourceType = typeof(Resources.Global))]
    public string City { get; set; }

In my BasicDetailsView.cshtml,

<label>
<span class="td">@Application.Resources.Global.State</span>
 @Html.DropDownListFor(m => m.State, (List<SelectListItem>)ViewData["State"])
</label>
<label>
<span class="td">@Application.Resources.Global.City</span>
@Html.DropDownListFor(m => m.City, (List<SelectListItem>)ViewData["City"])
</label>

If the state property returns true, then only "City" is required. If not, City is not required, then the textbox should be diabled. I'm not using EditorFor, using DropDownListFor because i'm using plain html. Can anyone help me to solve this issue? Thanks...

4
  • I'm not using EditorFor, using TextBoxFor - Where is this TextBoxFor? I can't see it in the code you have shown. All I can see is 2 dropdown lists (which by the way are wrong because you are using the same property name for both the value and the items). Commented Dec 29, 2012 at 10:57
  • @DarinDimitrov, corrected. How can we do this? Commented Dec 29, 2012 at 10:59
  • @DarinDimitrov my ViewData["city"] has a collection of SelectItem which has a different id, value for each. Commented Dec 29, 2012 at 11:03
  • But then you should not use City as first argument of your DropDown. Or rename the value in your ViewData to ViewData["cities"]. Commented Dec 29, 2012 at 11:05

2 Answers 2

3

MVC Foolproof is a set of validation data annotations that extend the existing ones and provide additional functionality. For example the [RequiredIfNotEmpty] attribute from this package is quite suitable for your scenario as it allows for conditional validation.

[Display(Name = "State", ResourceType = typeof(Resources.Global))]
public string State { get; set; }

[RequiredIfNotEmpty("State")]
[Display(Name = "City", ResourceType = typeof(Resources.Global))]
public string City { get; set; }

Now the State property is optional. But if it has some value then the City property is required.

Sign up to request clarification or add additional context in comments.

Comments

0

You might want to look at RequiredIfAttribute. To make your city dropdownlist disabled - use jquery. For checking if data is valid you have js method $("selector").valid() which returns 0 or 1 and also shows validation message for specified field

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.