现在这是一个直截了当的问题。因为您所有的个人NameViewModel 项目都需要保留其唯一名称,以便 MVC 模型绑定器可以正确识别和绑定您的模型。 (我相信你已经猜到了)。
所以现在我们没有单选按钮控件的名称来管理“组”。该名称还用于 HTTP Post 中以标识控件的值。所以现在我们处于第 22 阶段,模型绑定器需要唯一的名称才能在发布时绑定模型,而浏览器需要所有名称都与您所说的相同。
现在您可以使用一些 jQuery voodoo 来执行此操作,例如绑定另一个 data-,然后绑定到具有此名称的每个控件的单击事件。现在我认为这更像是一种 hack 而不是解决方案,但可以做类似的事情。 (是的,这是基本的)
假设这个模型
public class PersonViewModel
{
public PersonViewModel()
{
this.Names = new List<NameViewModel>();
}
public IList<NameViewModel> Names { get; set; }
}
public class NameViewModel
{
public NameViewModel()
{
this.IsPrimary = false;
}
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public bool IsPrimary { get; set; }
public string FullName
{
get
{
return string.Format("{0}{1} {2}",
this.FirstName,
!string.IsNullOrWhiteSpace(this.MiddleName) ? " " + this.MiddleName : "",
this.LastName);
}
}
标记
@Html.RadioButtonFor(x => x.Names[i].IsPrimary, true, new { data_group = "myGroup" })
Javascript
$(function () {
$('input[type="radio"][data-group="myGroup"]').click(function () {
$('input[type="radio"][data-group="myGroup"]').removeAttr('checked');
$(this).attr('checked', 'checked')
});
});
现在这将为您提供您所描述的结果。现在另一种选择(假设使用上述模型)我们向PrimaryName 的PersonViewModel 添加另一个属性,并将其设置为NameViewModel 的ID(或主键)。使您的 PersonViewModel 看起来像。
public class PersonViewModel
{
public PersonViewModel()
{
this.Names = new List<NameViewModel>();
}
public IList<NameViewModel> Names { get; set; }
public int PrimaryName { get; set; }
}
然后你的标记为。
@Html.RadioButton("PrimaryName", name.ID, name.IsPrimary)
@Html.HiddenFor(x => x.Names[i].ID)
现在这也有效,但现在将 PersonViewModel 的“PrimaryName”设置为已检查的 NameViewModel 的 ID。但是,您的 NameViewModel 将丢失 Post 上的 IsPrimary 值,因为我们不会将该值传回。要同时做到这两个,您必须将这两个选项组合起来。
希望这可以帮助您朝着正确的方向前进。任何一种方法(或其他方法)都应该有效。