我想在我的表单中显示一个单选按钮,该按钮将从模型数据中填充。
这是我的模型
public class Student
{
[Required(ErrorMessage = "First Name Required")] // textboxes will show
[Display(Name = "First Name :")]
[StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name Required")] // textboxes will show
[Display(Name = "Last Name :")]
[StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Sex Required")] // group of radio button will show
[Display(Name = "Sex :")]
public List<Sex> Sex { get; set; }
}
public class Sex
{
public string ID { get; set; }
public string Type { get; set; }
}
在这里,我试图从像这样的操作方法手动填充学生模型
public ActionResult Index()
{
var student= new Student
{
FirstName = "Rion",
LastName = "Gomes",
Sex= new List<Sex>
{
new Sex{ID="1" , Type = "Male"},
new Sex{ID="2" , Type = "Female"}
}
}
return View(student);
}
现在我怎么能生成一个单选按钮,它display text in form Male & Female
的值将具有ID
我搜索了谷歌并找到了许多样本,我使用了一个但不确定它是否有效。这是视图中的单选按钮代码。
@Html.RadioButtonFor(x => x.Sex, "Male")
我不想硬编码男性或女性;我想通过模型展示它,并想在 for 循环中生成单选按钮。
我也是MVC新手,所以请指导我。