I have the following Address ViewModel:
public class AddressViewModel
{
[StringLength(20, MinimumLength = 2, ErrorMessage = "Country name is too short")]
public String Country { get; set; }
public String City { get; set; }
public String Street { get; set; }
public String Number { get; set; }
public String ApartmentBuilding { get; set; }
public String Sector { get; set; }
}
And the view that renders it:
<div class="control-group offset2 span6">
@Html.LabelFor(m => m.Country)
<div class="controls">
@{
var countryCtrlName = Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName("Country");
Html.RenderAction("List", "Country", new { ControlName = countryCtrlName });
}
@Html.ValidationMessageFor(m => m.Country)
</div>
</div>
Html.RenderAction("List") calls a controller method that gets all countries from the database and renders and renders a partial with the dropdown, here's the view:
@model IEnumerable<SelectListItem>
@{var controlName = (string)ViewBag.ControlName;}
@Html.DropDownList(controlName, Model, new {@class = ViewBag.CssClass})
Even though my DropdownList control is rendered with the correct name and thus mapped to the correct ViewModel upon POST, the input control isn't decorated with the necessary data-val attributes to enable client-side validation (I believe this is because the model for the partial is IEnumerable instead of the the string property that holds the country name.
The address view model is used through my application as a nested property on many views. Any ideas on how to make it validate?
Edit: updated ViewModel based on @Robert's answer:
public class AddressViewModel { [StringLength(20, MinimumLength = 2, ErrorMessage = "Country name is too short")] public String Country { get; set; }
public String City { get; set; }
public String Street { get; set; }
public String Number { get; set; }
public String ApartmentBuilding { get; set; }
public String Sector { get; set; }
public IEnumerable<CountryViewModel> CountryList {get; set;}
//Constructor to pass the list of countries
public AddressViewModel(IEnumerable<CountryViewModel> countries)
{
this.CountryList = countries;
}
}
KDropDownList
. Google tells me it's part ofKeyoti.Search
. Is that correct? – Ann L.