我需要创建一个简单的单选按钮列表选择,以便从以下值中进行选择:
我们如何在以下剃刀视图中添加它?是否最好在QuestionModel
中创建这些值的枚举,并使用foreach
与html帮助器绑定。
任何一个例子或想法?
@model Survey.Models.Question
@using (Html.BeginForm("Index", "Home", new { QuestionId = Model.QuestionId }))
{
<h2>Survey</h2>
<fieldset>
<legend>Please Choose</legend>
<p>
Question ID:
@Model.QuestionId
</p>
<p>
Description:
@Model.Description
</p>
<input type="submit" value="Next" id="submitButton" />
</fieldset>
}
答案 0 :(得分:11)
使用ASP.NET Html Helpers,您可以为为单选按钮提供的每个不同帮助程序使用三种不同的方法。
方法1
制作单选按钮列表的简单方法:
<div>
<label>
@Html.RadioButton("Answer", "Agree")
Agree
</label>
</div>
<div>
<label>
@Html.RadioButton("Answer", "Disagree")
Disagree
</label>
</div>
<div>
<label>
@Html.RadioButton("Answer", "Not Sure")
Not Sure
</label>
</div>
方法2
以上代码将使用&#34;回答&#34;的名称发布选中的值。单击“提交”到服务器。如果您想像在Model.QuestionId和Model.Description中那样强类型化,可以在模型中添加Answer属性并执行以下操作:
<div>
<label>
@Html.RadioButtonFor(m => m.Answer, "Agree")
Agree
</label>
</div>
<div>
<label>
@Html.RadioButtonFor(m => m.Answer, "Disagree")
Disagree
</label>
</div>
<div>
<label>
@Html.RadioButtonFor(m => m.Answer, "Not Sure")
Not Sure
</label>
</div>
方法3
最后,如果您想获得幻想,可以使用枚举。将以下内容放在您的控制器中:
public enum AnswerType {
Agree,
Disagree,
NotSure
}
接下来,将属性添加到模型中:
public AnswerType AnswerType { get; set; }
然后将以下内容添加到您的视图中:
@Html.RadioButtonForEnum(m => m.AnswerType)
希望这有帮助!
答案 1 :(得分:2)
这会奏效 模型的单选按钮
@using (Html.BeginForm())
{
foreach (var department in Model.Departments)
{
@Html.RadioButtonFor(m => m.SelectedDepartment, department.Id) @department.Name
}
<input type="submit" value="Submit" />
}
答案 2 :(得分:0)
在您的viewmodel中,您可以拥有一个public int SelectedRating。您可以将其设置为字符串,并将值从114 ...更改为字符串值。
@ Html.RadioButtonFor(x =&gt; x.SelectedRating,114) 不确定 <div class="radio">
<label>
@Html.RadioButtonFor(x => x.SelectedRating, 115)
<span>Agree</span>
</label>
</div>
<div class="radio">
<label>
@Html.RadioButtonFor(x => x.SelectedRating, 116)
<span>Don't Agree</span>
</label>
</div>