MVC Radiobutton 绑定复杂对象 [英] MVC Radiobutton binding complex object

查看:22
本文介绍了MVC Radiobutton 绑定复杂对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 MVC3 Web 应用程序,我们需要在其中使用验证填充单选按钮列表.我的模型是这样的:

公共类EmployeesViewModel{公共列表<员工>listEmployee { 得到;放;}//在发布期间持久化公共 IEnumerable<SelectListItem>selectListEmployee { 得到;放;}[必需的]公共雇员选择雇员{得到;放;}}公共类员工{公共 int ID {get;放;}公共字符串名称 {get;放}公共字符串系{get;放}}

我需要填充单选按钮列表,如下所示:

  • Employee1ID - Employee1Name - Employee1Department//id - 姓名 - 部门
  • Employee2ID - Employee2Name - Employee2Department
  • Employee3ID - Employee3Name - Employee3Department

选定的员工应存储在selectedEmployee"字段中.在 MVC3 中填充这些单选按钮列表的最佳或干净的方法是什么?

注意:主要找两个任务:1. 在每个Input"单选按钮标签中存储Employee"对象,以便将选中的员工保存到selectedEmployee"字段中2. 将Employee"对象标记为必填字段的最佳方法

非常感谢您的帮助!

谢谢,

解决方案

这是我向您推荐的.从一个干净的视图模型开始,它真正将视图包含的内容表达为信息:

公共类EmployeesViewModel{公共列表<EmployeeViewModel>ListEmployee { 得到;放;}[必需的]公共诠释?SelectedEmployeeId { 得到;放;}}公共类 EmployeeViewModel{公共 int ID { 获取;放;}公共字符串标签 { 获取;放;}}

然后是控制器:

公共类 HomeController : 控制器{公共行动结果索引(){var 模型 = 新员工视图模型{ListEmployee = GetEmployees()};返回视图(模型);}[HttpPost]公共 ActionResult 索引(EmployeesViewModel 模型){if (!ModelState.IsValid){//模型无效,用户没有选择员工//=>从存储库中重新获取员工列表并//重新显示视图以便他可以修复错误model.ListEmployee = GetEmployees();返回视图(模型);}//在这个阶段通过验证//TODO: model.SelectedEmployeeId 将包含 id//所选员工的 =>使用您的存储库获取//实际的员工对象并用它做一些事情//(比如授予他当月奖的员工 :-))return Content("感谢提交", "text/plain");}//TODO: 这显然不属于这里//这仅用于演示目的.在真实//应用程序你有一个存储库,使用 DI,...私有列表<EmployeeViewModel>获取雇员(){返回新的[]{新的 EmployeeViewModel { ID = 1,标签 = "John (HR)" },新的 EmployeeViewModel { ID = 2,标签 =彼得(IT)"},新的 EmployeeViewModel { ID = 3, Label = "Nathalie (Sales)" },}.ToList();}}

最后是一个视图:

@modelEmployeesViewModel@using (Html.BeginForm()){@Html.ValidationMessageFor(x => x.SelectedEmployeeId)@foreach(Model.ListEmployee 中的 var 员工){

@Html.RadioButtonFor(x => x.SelectedEmployeeId, employee.ID, new { id = "emp" + employee.ID })@Html.Label("emp" +employee.ID,employee.Label)</div>}<输入类型=提交"值=确定"/>}

I have MVC3 web application where we need to populate radio button list with validation. My Model is something like this:

public class EmployeesViewModel
{
     public List<Employee> listEmployee { get; set; } //To persist during post
     public IEnumerable<SelectListItem> selectListEmployee { get; set; }

     [Required]
     public Employee selectedEmployee { get; set; }
}

public class Employee
{
  public int ID {get; set;}
  public string Name {get; set}
  public string Department {get; set}
 }

I need to populate radiobutton list something like below:

  • Employee1ID - Employee1Name - Employee1Department // id - name - department
  • Employee2ID - Employee2Name - Employee2Department
  • Employee3ID - Employee3Name - Employee3Department

Selected Employee should be stored into "selectedEmployee" field. What is the best or clean way to populate these radio button List in MVC3?

Note: Mainly Looking for two task: 1. storing "Employee" object in each "Input" radio button tag, so that selected employee will be saved to "selectedEmployee" field 2. Best way to mark "Employee" object as required field

Much appreciate your help!

Thanks,

解决方案

Here's what I would recommend you. Start with a clean view model, one that really expresses what the view contains as information:

public class EmployeesViewModel
{
    public List<EmployeeViewModel> ListEmployee { get; set; }

    [Required]
    public int? SelectedEmployeeId { get; set; }
}

public class EmployeeViewModel
{
    public int ID { get; set; }
    public string Label { get; set; }
}

then a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new EmployeesViewModel
        {
            ListEmployee = GetEmployees()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(EmployeesViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // the model is invalid, the user didn't select an employee
            // => refetch the employee list from the repository and
            // redisplay the view so that he can fix the errors
            model.ListEmployee = GetEmployees();
            return View(model);
        }

        // validation passed at this stage
        // TODO: model.SelectedEmployeeId will contain the id
        // of the selected employee => use your repository to fetch the
        // actual employee object and do something with it 
        // (like grant him the employee of the month prize :-))

        return Content("thanks for submitting", "text/plain");
    }

    // TODO: This doesn't belong here obviously
    // it's only for demonstration purposes. In the real 
    // application you have a repository, use DI, ...
    private List<EmployeeViewModel> GetEmployees()
    {
        return new[]
        {
            new EmployeeViewModel { ID = 1, Label = "John (HR)" },
            new EmployeeViewModel { ID = 2, Label = "Peter (IT)" },
            new EmployeeViewModel { ID = 3, Label = "Nathalie (Sales)" },
        }.ToList();
    }
}

and finally a view:

@model EmployeesViewModel

@using (Html.BeginForm())
{
    @Html.ValidationMessageFor(x => x.SelectedEmployeeId)
    @foreach (var employee in Model.ListEmployee)
    {
        <div>
            @Html.RadioButtonFor(x => x.SelectedEmployeeId, employee.ID, new { id = "emp" + employee.ID })
            @Html.Label("emp" + employee.ID, employee.Label)
        </div>
    }
    <input type="submit" value="OK" />
}

这篇关于MVC Radiobutton 绑定复杂对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆