3

In my viewModel I have

public string Addressline1 { get; set; }
public List<SelectListItem> StateList
    {
        get
        {
            return State.GetAllStates().Select(state => new SelectListItem { Selected = false, Text = state.Value, Value = state.Value }).ToList();
        }
    }

In the view I have

@Html.DropDownListFor(model => model.StateCode, Model.StateList, "select")

when AddressLine1 is entered, then the statelist DropDownList selection is Required.How do I validate and show an error message when no state is selected in the Drop down list other than default "select" value?

1
  • But the drop down list selection is required only when AddressLine1 is entered. How can I handle this in the viewModel? Commented Jul 21, 2011 at 20:53

1 Answer 1

7

Decorate your StateCode property with the [Required] attribute:

[Required(ErrorMessage = "Please select a state")]
public string StateCode { get; set; }

public IEnumerable<SelectListItem> StateList
{
    get
    {
        return State
            .GetAllStates()
            .Select(state => new SelectListItem 
            { 
                Text = state.Value, 
                Value = state.Value 
            })
            .ToList();
    }
}

and then you could add a corresponding validation error message:

@Html.DropDownListFor(model => model.StateCode, Model.StateList, "select")
@Html.ValidationMessageFor(model => model.StateCode)

UPDATE:

Alright it seems that you want to conditionally validate this StateCode property depending on some other property on your view model. Now that's an entirely different story and you should have explained this in your original question. Anyway, one possibility is to write a custom validation attribute:

public class RequiredIfPropertyNotEmptyAttribute : ValidationAttribute
{
    public string OtherProperty { get; private set; }
    public RequiredIfPropertyNotEmptyAttribute(string otherProperty)
    {
        if (otherProperty == null)
        {
            throw new ArgumentNullException("otherProperty");
        }
        OtherProperty = otherProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(OtherProperty);
        if (property == null)
        {
            return new ValidationResult(string.Format(CultureInfo.CurrentCulture, "{0} is an unknown property", new object[]
            {
                OtherProperty
            }));
        }
        var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null) as string;
        if (string.IsNullOrEmpty(otherPropertyValue))
        {
            return null;
        }

        if (string.IsNullOrEmpty(value as string))
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }

        return null;
    }
}

and now decorate your StateCode property with this attribute, like so:

public string AddressLine1 { get; set; }

[RequiredIfPropertyNotEmpty("AddressLine1", ErrorMessage = "Please select a state")]
public string StateCode { get; set; }

Now assuming you have the following form:

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.AddressLine1)
        @Html.EditorFor(x => x.AddressLine1)
    </div>

    <div>
        @Html.LabelFor(x => x.StateCode)
        @Html.DropDownListFor(x => x.StateCode, Model.States, "-- state --")
        @Html.ValidationMessageFor(x => x.StateCode)
    </div>

    <input type="submit" value="OK" />
}

the StateCode dropdown will be required only if the user entered a value into the AddressLine1 field.

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

2 Comments

But the drop down list selection is required only when AddressLine1 is entered. How can I handel this in the viewModel?
@Theja Kotagir, please see my updated answer in which I present one possible solution for this requirement that you should have clearly stated in your original question.

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.