0

我有一个强类型视图,它保存控件(输入框)来表示一个集合项。例如,以添加员工详细信息的视图为例,其中有一组可变的输入字段用于输入部门名称。这些输入字段将在客户端动态添加。

这是这两个实体的类结构:

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; }

}

部门名称的输入是动态生成的,名称的设置方式是发布后实现模型绑定

<input type='text' class='input-choice' id='txtChoice0' name='Department[0].Name' />

现在我的问题是我应该如何对此应用验证?Microsoft Validation 不会在 mvcClientValidationMetadata 内推送验证,我认为这是因为框架在视图加载时没有看到任何模型绑定发生。

有任何想法吗 ??

4

1 回答 1

1

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

于 2012-05-03T23:13:47.430 回答