MVC Radiobutton binding complex object

后端 未结 1 1387
庸人自扰
庸人自扰 2020-12-19 11:09

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

public class EmployeesViewModel
{
          


        
相关标签:
1条回答
  • 2020-12-19 11:36

    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" />
    }
    
    0 讨论(0)
提交回复
热议问题