这里就是我会推荐你。开始用干净的视图模型,一个真正表达什么视图包含的信息:
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; }
}
然后控制器:
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();
}
}
最后一个观点:
@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" />
}
感谢达林!该视图模型真的有用! – matmat
寻找来自你的更多想法。让我说在我的情况下,如果我在我的“员工”表中有复合键? (比如“ID”和“Department”一起形成复合键)在这种情况下,我需要传递ID和Department以获得我想要的真实对象。什么是最好的方式来做到这一点? – matmat
@matmat,一个单选按钮只发送一个值,所以在这种情况下使用复合键是没有意义的。您可以使用数据库的唯一主键。作为一种替代方案,您可以让ID属性为'ID_DEPT'形式的字符串,当表单被回发并获取两个值但似乎令人讨厌时,您可以在控制器中将其分割。一个独特的主键是一个更好的方法。 –