使用 .net MVC RadioButtonFor() 时,如何分组以便只能进行一个选择? [英] When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

查看:23
本文介绍了使用 .net MVC RadioButtonFor() 时,如何分组以便只能进行一个选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个让我很难过,我有一个强类型视图,它有这个循环来生成单选按钮:

<% foreach (Model.QuestionAnswers 中的QuestionAnswer qa){%><%= Html.RadioButtonFor(model => model.QuestionAnswers[(int)qa.QuestionID - 1].AnswerValue, "Checked" ) %><%=Html.Encode(qa.OptionValue)%><%}%>

它呈现得很好,但由于名称不同,您可以选择 1 个以上的单选按钮.如何将它们分组以便只能选择 1 个单选按钮?

任何帮助将不胜感激!

解决方案

Html.RadioButtonFor() 的第一个参数应该是你正在使用的属性名称,第二个参数应该是那个特定单选按钮的值.然后它们将具有相同的 name 属性值,当/如果它与属性值匹配时,助手将选择给定的单选按钮.

示例:

<%=Html.RadioButtonFor(m=>m.Gender, "M")%>男性<%= Html.RadioButtonFor(m => m.Gender, "F") %>女性

这是一个更具体的例子:

我创建了一个名为DeleteMeQuestion"的快速 MVC 项目(DeleteMe 前缀,所以我知道我可以在忘记它后将其删除).

我制作了以下模型:

命名空间 DeleteMeQuestion.Models{公共类 QuizModel{公共 int ParentQuestionId { 获取;放;}公共 int QuestionId { 获取;放;}公共字符串 QuestionDisplayText { 获取;放;}公共列表<响应>回应 { 得到;放;}[Range(1,999, ErrorMessage = "请选择一个响应.")]公共 int SelectedResponse { 获取;放;}}公开课回应{公共 int ResponseId { 获取;放;}公共 int ChildQuestionId { 获取;放;}公共字符串 ResponseDisplayText { 获取;放;}}}

模型中有一个简单的范围验证器,只是为了好玩.接下来,我制作了以下控制器:

命名空间 DeleteMeQuestion.Controllers{[处理错误]公共类 HomeController : 控制器{公共 ActionResult 索引(int?id){//TODO:根据方法参数获取要显示的问题var 模型 = GetModel(id);返回视图(模型);}[HttpPost]公共 ActionResult 索引(int?id,QuizModel 模型){如果 (!ModelState.IsValid){var freshModel = GetModel(id);返回视图(新鲜模型);}//TODO: 将选定的答案保存在数据库中//TODO:根据选择的答案获取下一个问题(目前硬编码为 999)var nextQuestionId = 999;return RedirectToAction("Index", "Home", new {id = nextQuestionId});}私人 QuizModel GetModel(int? questionId){//只是一个存根,代替数据库var 模型 = 新的 QuizModel{QuestionDisplayText = questionId.HasValue ?等等……":你最喜欢什么颜色?",问题 ID = 1,响应 = 新列表<响应>{新回复{ChildQuestionId = 2,响应 ID = 1,ResponseDisplayText = "红色"},新回复{ChildQuestionId = 3,响应 ID = 2,ResponseDisplayText = "蓝色"},新回复{ChildQuestionId = 4,响应 ID = 3,ResponseDisplayText = "绿色"},}};退货模式;}}}

最后,我做了以下使用模型的视图:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage"%><asp:Content ContentPlaceHolderID="TitleContent" runat="server">主页</asp:内容><asp:Content ContentPlaceHolderID="MainContent" runat="server"><% using (Html.BeginForm()) {%><div><h1><%:Model.QuestionDisplayText %</h1><div><ul><% foreach(Model.Responses 中的 var item){%><li><%= Html.RadioButtonFor(m => m.SelectedResponse, item.ResponseId, new {id="Response" + item.ResponseId}) %><label for="Response<%: item.ResponseId %>"><%: item.ResponseDisplayText %></label><%}%><%=Html.ValidationMessageFor(m=>m.SelectedResponse)%>

<input type="submit" value="Submit"/><%}%></asp:内容>

据我了解您的情况,您有问题并附有可用答案列表.每个答案将决定下一个问题.希望从我的模型和 TODO 评论中可以看出这一点.

这为您提供了具有相同名称属性但不同 ID 属性的单选按钮.

This one has me stumped, I have a strongly typed view that has this loop to generate radiobuttons:

<% foreach (QuestionAnswer qa in Model.QuestionAnswers)
   { %>
    <%= Html.RadioButtonFor(model => model.QuestionAnswers[(int)qa.QuestionID - 1].AnswerValue, "Checked" ) %>
    <%= Html.Encode(qa.OptionValue) %>
<% } %>

It renders fine, but since the names are not the same, you can select more than 1 radiobutton. How can I group them so only 1 radiobutton can be selected?

Any help would be appreciated!

解决方案

The first parameter of Html.RadioButtonFor() should be the property name you're using, and the second parameter should be the value of that specific radio button. Then they'll have the same name attribute value and the helper will select the given radio button when/if it matches the property value.

Example:

<div class="editor-field">
    <%= Html.RadioButtonFor(m => m.Gender, "M" ) %> Male
    <%= Html.RadioButtonFor(m => m.Gender, "F" ) %> Female
</div>

Here's a more specific example:

I made a quick MVC project named "DeleteMeQuestion" (DeleteMe prefix so I know that I can remove it later after I forget about it).

I made the following model:

namespace DeleteMeQuestion.Models
{
    public class QuizModel
    {
        public int ParentQuestionId { get; set; }
        public int QuestionId { get; set; }
        public string QuestionDisplayText { get; set; }
        public List<Response> Responses { get; set; }

        [Range(1,999, ErrorMessage = "Please choose a response.")]
        public int SelectedResponse { get; set; }
    }

    public class Response
    {
        public int ResponseId { get; set; }
        public int ChildQuestionId { get; set; }
        public string ResponseDisplayText { get; set; }
    }
}

There's a simple range validator in the model, just for fun. Next up, I made the following controller:

namespace DeleteMeQuestion.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(int? id)
        {
            // TODO: get question to show based on method parameter 
            var model = GetModel(id);
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(int? id, QuizModel model)
        {
            if (!ModelState.IsValid)
            {
                var freshModel = GetModel(id);
                return View(freshModel);
            }

            // TODO: save selected answer in database
            // TODO: get next question based on selected answer (hard coded to 999 for now)

            var nextQuestionId = 999;
            return RedirectToAction("Index", "Home", new {id = nextQuestionId});
        }

        private QuizModel GetModel(int? questionId)
        {
            // just a stub, in lieu of a database

            var model = new QuizModel
            {
                QuestionDisplayText = questionId.HasValue ? "And so on..." : "What is your favorite color?",
                QuestionId = 1,
                Responses = new List<Response>
                                                {
                                                    new Response
                                                        {
                                                            ChildQuestionId = 2,
                                                            ResponseId = 1,
                                                            ResponseDisplayText = "Red"
                                                        },
                                                    new Response
                                                        {
                                                            ChildQuestionId = 3,
                                                            ResponseId = 2,
                                                            ResponseDisplayText = "Blue"
                                                        },
                                                    new Response
                                                        {
                                                            ChildQuestionId = 4,
                                                            ResponseId = 3,
                                                            ResponseDisplayText = "Green"
                                                        },
                                                }
            };

            return model;
        }
    }
}

Finally, I made the following view that makes use of the model:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DeleteMeQuestion.Models.QuizModel>" %>

<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">

    <% using (Html.BeginForm()) { %>

        <div>

            <h1><%: Model.QuestionDisplayText %></h1>

            <div>
            <ul>
            <% foreach (var item in Model.Responses) { %>
                <li>
                    <%= Html.RadioButtonFor(m => m.SelectedResponse, item.ResponseId, new {id="Response" + item.ResponseId}) %>
                    <label for="Response<%: item.ResponseId %>"><%: item.ResponseDisplayText %></label>
                </li>
            <% } %>
            </ul>

            <%= Html.ValidationMessageFor(m => m.SelectedResponse) %>

        </div>

        <input type="submit" value="Submit" />

    <% } %>

</asp:Content>

As I understand your context, you have questions with a list of available answers. Each answer will dictate the next question. Hopefully that makes sense from my model and TODO comments.

This gives you the radio buttons with the same name attribute, but different ID attributes.

这篇关于使用 .net MVC RadioButtonFor() 时,如何分组以便只能进行一个选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆