如何在mvc4中使用radiobuttonlist

rum*_*umi 4 asp.net-mvc razor asp.net-mvc-4

我需要创建一个简单的单选按钮列表选择,以便从以下值中进行选择:

  • 同意
  • 不同意
  • 不确定

我们如何在以下剃刀视图中添加它?是否更好地创建这些值的枚举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>

}
Run Code Online (Sandbox Code Playgroud)

小智 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> 
Run Code Online (Sandbox Code Playgroud)

方法2

单击"提交"时,上面的代码将向服务器发布名为"Answer"的已检查值.如果您想像在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>
Run Code Online (Sandbox Code Playgroud)

方法3

最后,如果您想获得幻想,可以使用枚举.将以下内容放在您的控制器中:

public enum AnswerType {
    Agree,
    Disagree,
    NotSure
}
Run Code Online (Sandbox Code Playgroud)

接下来,将属性添加到模型中:

public AnswerType AnswerType { get; set; }
Run Code Online (Sandbox Code Playgroud)

然后将以下内容添加到您的视图中:

@Html.RadioButtonForEnum(m => m.AnswerType)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!


小智 0

在您的视图模型中,您可以有一个 public int SelectedRating。您可以将其设置为字符串并将值从 114... 更改为字符串值。

<div class="radio">
   <label>
      @Html.RadioButtonFor(x => x.SelectedRating, 114)
      <span>Not Sure</span>
   </label>
</div>
<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>
Run Code Online (Sandbox Code Playgroud)