且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Asp.net mvc中的模型绑定单选按钮列表

更新时间:2023-02-25 08:15:52

Step1 :定义问题和选项模型

Step1: Define Question and Option model
public class Question
{
    public decimal TestId { get; set; }
    public decimal SkillId { get; set; }
    public decimal ID { get; set; }
    public string QuestionText { get; set; }
    public List<OptionList> Options { set; get; }
	public string SelectedAnswer { get; set; }	
}

public class OptionList
{
    public string Option1 { get; set; }
    public string Option2 { get; set; }
    public string Option3 { get; set; }
    public string Option4 { get; set; }
}



Step2 :设计视图页面并添加viewmodel顶视图页。


Step2: Design View page and add your viewmodel top of view page.

@model yourproject.model.Question; // Change as per your requirement
foreach (var temp in Model.Options)
{
	<div>
		@Html.RadioButtonFor(model => Model.SelectedAnswer, "1"})
		@Html.Label(temp.Option1)
	</div>
	<div>
		@Html.RadioButtonFor(model => Model.SelectedAnswer, "2")
		@Html.Label(temp.Option2)
	</div>
	<div>
		@Html.RadioButtonFor(model => Model.SelectedAnswer, "3")
		@Html.Label(temp.Option3)
	</div>
	<div>
		@Html.RadioButtonFor(model => Model.SelectedAnswer, "4")
		@Html.Label(temp.Option4)
	</div>
}



Step3 :在Controller中添加一个动作来获取价值


Step3: Add an action in Controller to get value

[HttpPost]
public AcitonResult Index(Question qModel)
{
    if (ModelState.IsValid)
    {
        //TODO: Save your model and redirect 
	string temp = qModel.SelectedAnswer;
    }

    return View();
}