Reputation: 1943
I have a strongly typed view, which hold controls(input boxes) to represent a collection item. So for an example , take case of a view for adding an Employee detail and within that there are variable set of input fields to enter Department name. These input fields are to be added dynamically at client side.
Here is the class structure of these two entities:
public class Employee
{
public int EmployeeID{get;set;}
public string Name {get;set; }
public IList<Department> DepartmentList{get;set;}
}
public class Deparment {
[Required(ErrorMessage="This is a required Field")]
public string Name {get;set; }
public int ID { get;set; }
}
Inputs for department names are generated dynamically and names are set in a way to achieve model binding after posting
<input type='text' class='input-choice' id='txtChoice0' name='Department[0].Name' />
Now my question is how should I apply validation to this ?. Microsoft Validation won't push the validation inside the mvcClientValidationMetadata , reason for this I assume is that framework doesn't see any model binding happening at the time of view load.
Any ideas ??
Upvotes: 1
Views: 1114
Reputation: 4361
I believe what you are asking for is how to validate values from the dropdownlist with 'Required' attribute. You will need to make some changes to the Employee model.
First of all you will need a 'DepartmentCode' property coz you will be storing the selected Department code from the dropdown.
Then you can have the DepartmentList as IEnumerable<SelectListItem>
so your Employee model will look like
public class Employee
{
public int EmployeeID{get;set;}
public string Name {get;set; }
[Required(ErrorMessage = "Please select a department")]
public string DepartmentCode { get; set; }
public IEnumerable<SelectListItem> DepartmentList{get;set;
}
you can get the DepartmentList like this
public IEnumerable<SelectListItem> DepartmentList
{
get
{
//Your code to return the departmentlist as a SelectedListItem collection
return Department
.GetAllDepartments()
.Select(department => new SelectListItem
{
Text = department.Name,
Value = department.ID.ToString()
})
.ToList();
}
}
finally in the view
<%: Html.DropDownListFor(model => model.DepartmentCode, Model.DepartmentList, "select")%>
<%: Html.ValidationMessageFor(model => model.DepartmentCode)%>
Now when you try to submit without selecting a department it should be validated
Upvotes: 1