ASP.NET MVC 复选框组 [英] ASP.NET MVC Checkbox Group

查看:16
本文介绍了ASP.NET MVC 复选框组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试针对 ASP.NET MVC 中缺少复选框组"的问题制定解决方法.实现这一点的典型方法是使用相同名称的复选框,每个复选框都有它所代表的值.

I am trying to formulate a work-around for the lack of a "checkbox group" in ASP.NET MVC. The typical way to implement this is to have check boxes of the same name, each with the value it represents.

<input type="checkbox" name="n" value=1 />
<input type="checkbox" name="n" value=2 />
<input type="checkbox" name="n" value=3 />

提交时,它将以逗号分隔请求项n"的所有值..因此,如果提交时所有三个都被选中,则请求[n"] ==1,2,3".在 ASP.NET MVC 中,你可以有一个参数 n 作为一个数组来接受这个帖子.

When submitted, it will comma delimit all values to the request item "n".. so Request["n"] == "1,2,3" if all three are checked when submitted. In ASP.NET MVC, you can have a parameter of n as an array to accept this post.

public ActionResult ActionName( int[] n ) { ... }

以上所有工作都正常.我遇到的问题是,当验证失败时,复选框不会恢复到选中状态.任何建议.

All of the above works fine. The problem I have is that when validation fails, the check boxes are not restored to their checked state. Any suggestions.

问题代码:(我从默认的asp.net mvc项目开始)

Problem Code: (I started with the default asp.net mvc project)

控制器

    public class HomeController : Controller
    {
        public ActionResult Index()
        {   var t = getTestModel("First");
            return View(t);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(TestModelView t)
        {   if(String.IsNullOrEmpty( t.TextBoxValue))
                ModelState.AddModelError("TextBoxValue", "TextBoxValue required.");
            var newView = getTestModel("Next");
            return View(newView);
        }

        private TestModelView getTestModel(string prefix)
        {   var t = new TestModelView();
            t.Checkboxes = new List<CheckboxInfo>()
            {   new CheckboxInfo(){Text = prefix + "1", Value="1", IsChecked=false},
                new CheckboxInfo(){Text = prefix + "2", Value="2", IsChecked=false} 
            };
            return t;
        }
    }
    public class TestModelView
    {   public string TextBoxValue { get; set; }
        public List<CheckboxInfo> Checkboxes { get; set; }
    }
    public class CheckboxInfo
    {   public string Text { get; set; }
        public string Value { get; set; }
        public bool IsChecked { get; set; }
    }
}

ASPX

<%
using( Html.BeginForm() ){ 
%>  <p><%= Html.ValidationSummary() %></p>
    <p><%= Html.TextBox("TextBoxValue")%></p>
    <p><%  
    int i = 0;
    foreach (var cb in Model.Checkboxes)
    { %>
        <input type="checkbox" name="Checkboxes[<%=i%>]" 
            value="<%= Html.Encode(cb.Value) %>" <%=cb.IsChecked ? "checked="checked"" : String.Empty %> 
            /><%= Html.Encode(cb.Text)%><br />
    <%      i++;
    } %></p>
    <p><input type="submit" value="submit" /></p>
<%
}
%>

工作代码

控制器

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(TestModelView t)
{
    if(String.IsNullOrEmpty( t.TextBoxValue))
    {   ModelState.AddModelError("TextBoxValue", "TextBoxValue required.");
        return View(t); 
    }
    var newView = getTestModel("Next");
    return View(newView);
}

ASPX

int i = 0;
foreach (var cb in Model.Checkboxes)
{ %>
    <input type="checkbox" name="Checkboxes[<%=i%>].IsChecked" <%=cb.IsChecked ? "checked="checked"" : String.Empty %> value="true" />
    <input type="hidden"   name="Checkboxes[<%=i%>].IsChecked" value="false" />
    <input type="hidden" name="Checkboxes[<%=i%>].Value" value="<%= cb.Value %>" />
    <input type="hidden" name="Checkboxes[<%=i%>].Text" value="<%= cb.Text %>" />
    <%= Html.Encode(cb.Text)%><br />
<%      i++;
} %></p>
<p><input type="submit" value="submit" /></p>

当然可以用 Html Helpers 做类似的事情,但这是有效的.

Of course something similar could be done with Html Helpers, but this works.

推荐答案

我不知道如何解决您的问题,但您可以使用以下代码定义复选框:

I don't know how to solve your problem, but you could define your checkboxes with this code:

<%= Html.CheckBox("n[0]") %><%= Html.Hidden("n[0]",false) %>
<%= Html.CheckBox("n[1]") %><%= Html.Hidden("n[1]",false) %>
<%= Html.CheckBox("n[2]") %><%= Html.Hidden("n[2]",false) %>

需要隐藏字段,因为如果未选中复选框,则表单不会发送任何值.使用隐藏字段发送错误.

Hidden fields are needed, because if checkbox is not checked, form doesn't send any value. With hidden field it sends false.

您的发布方法将是:

[HttpPost]
public ActionResult Test(bool[] n)
{
    return View();
}

它可能不是最佳的,我愿意接受评论,但它有效:)

It may not be optimal and I am open to comments, but it works:)

编辑

扩展版:

<%= Html.CheckBox("n[0].Checked") %><%= Html.Hidden("n[0].Value",32) %><%= Html.Hidden("n[0].Checked",false) %>
<%= Html.CheckBox("n[1].Checked") %><%= Html.Hidden("n[1].Value",55) %><%= Html.Hidden("n[1].Checked",false) %>
<%= Html.CheckBox("n[2].Checked") %><%= Html.Hidden("n[2].Value",76) %><%= Html.Hidden("n[2].Checked",false) %>

您的发布方法将是:

[HttpPost]
public ActionResult Test(CheckedValue[] n)
{
    return View();
}

public class CheckedValue
{
     public bool Checked { get; set; }
     public bool Value { get; set; }
}

我在没有 VS 的情况下写的,所以可能需要一点点修正.

I wrote it without VS, so it may need little correction.

这篇关于ASP.NET MVC 复选框组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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