如何在asp.net mvc中检索控制器中的复选框列表值

发布于 2024-08-30 05:31:28 字数 858 浏览 3 评论 0原文

我在视图页面中有一个如下所示的表单:

<form runat="server" id="dcrsubmit">
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem>test1</asp:ListItem>
<asp:ListItem>test2</asp:ListItem>
<asp:ListItem>test3</asp:ListItem>
<asp:ListItem>test4</asp:ListItem>
<asp:ListItem>test5</asp:ListItem>
<asp:ListItem>test6</asp:ListItem>
</asp:CheckBoxList>

....other controls
</form>

现在,当发布表单时,我尝试检索在控制器中提交的值,如下所示:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult testmethod(FormCollection formValues)
{
  string s = formvalues.get("CheckBoxList1");
   .
   .  /* other code */
   .
}

当我通过选中一些复选框提交表单时,字符串值显示 null。这是检索值的方法还是我做错了什么?而且我无法使用 html 控件,因为表单上的所有其他控件都是服务器控件,我不确定是否只能将此控件设为 html 控件。我不确定如何将值绑定到它?

I am having a form in a view page that looks as below:

<form runat="server" id="dcrsubmit">
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem>test1</asp:ListItem>
<asp:ListItem>test2</asp:ListItem>
<asp:ListItem>test3</asp:ListItem>
<asp:ListItem>test4</asp:ListItem>
<asp:ListItem>test5</asp:ListItem>
<asp:ListItem>test6</asp:ListItem>
</asp:CheckBoxList>

....other controls
</form>

Now when the form is posted, I am trying to retrieve the values submitted in the controller as below:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult testmethod(FormCollection formValues)
{
  string s = formvalues.get("CheckBoxList1");
   .
   .  /* other code */
   .
}

The string value shows null when I submit the form by checking some checkboxes. Is this the way to retrieve the values or am I doing something wrong? And I cannot use html control because all other controls on the form are server controls and I am not sure if I can only make this control a html control. And I am not sure how can I bind the values to it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

软甜啾 2024-09-06 05:31:28

MVCContrib 提供了一些优秀的扩展来提供许多控件,并且它们还有一个 CheckBoxList。

要开始使用 MVCContrib,阅读本文

您需要使用强类型视图并在视图中包含此导入语句:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.HomeModel>" %>
<%@ Import Namespace="MvcContrib.FluentHtml" %>

此示例有效。这是视图上的代码。

    <%= this.CheckBoxList("UserType").Options(Model.UserTypeOptions) %>

这是控制器。

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Submit(HomeModel viewModel)
    {
        if (viewModel.SelectedUserType == UserTypeEnum.Normal)
        {
            // do something
        }
        return View("Index", viewModel);
    }

这是模型。

public enum UserTypeEnum
{
    Administrator = 0,
    SuperUser,
    Supervisor,
    Normal,
}
public class HomeModel
{
    [Required]
    public string Name { get; set; }

    public List<SelectListItem> UserTypeOptions { get; set; }
    public string UserType { get; set; }

    public UserTypeEnum SelectedUserType
    {
        get
        {
            return (UserTypeEnum) Enum.Parse(typeof (UserTypeEnum), UserType);
        }
    }

    public HomeModel()
    {
        UserTypeOptions = new List<SelectListItem>
                       {
                           new SelectListItem{Text = "Administrator", Value = ((int)UserTypeEnum.Administrator).ToString()},
                           new SelectListItem{Text = "SuperUser", Value = ((int)UserTypeEnum.SuperUser).ToString()},
                           new SelectListItem{Text = "Supervisor", Value = ((int)UserTypeEnum.Supervisor).ToString()},
                           new SelectListItem{Text = "Normal", Value = ((int)UserTypeEnum.Normal).ToString()},
                       };
    }
}

MVCContrib supply some excellent extensions to provide many controls and they also have a CheckBoxList.

To get started with MVCContrib, read this

You'll need to use a strongly typed view and include this import statement in the view:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.HomeModel>" %>
<%@ Import Namespace="MvcContrib.FluentHtml" %>

This example works. Here is the code on the view.

    <%= this.CheckBoxList("UserType").Options(Model.UserTypeOptions) %>

Here is the controller.

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Submit(HomeModel viewModel)
    {
        if (viewModel.SelectedUserType == UserTypeEnum.Normal)
        {
            // do something
        }
        return View("Index", viewModel);
    }

Here is the model.

public enum UserTypeEnum
{
    Administrator = 0,
    SuperUser,
    Supervisor,
    Normal,
}
public class HomeModel
{
    [Required]
    public string Name { get; set; }

    public List<SelectListItem> UserTypeOptions { get; set; }
    public string UserType { get; set; }

    public UserTypeEnum SelectedUserType
    {
        get
        {
            return (UserTypeEnum) Enum.Parse(typeof (UserTypeEnum), UserType);
        }
    }

    public HomeModel()
    {
        UserTypeOptions = new List<SelectListItem>
                       {
                           new SelectListItem{Text = "Administrator", Value = ((int)UserTypeEnum.Administrator).ToString()},
                           new SelectListItem{Text = "SuperUser", Value = ((int)UserTypeEnum.SuperUser).ToString()},
                           new SelectListItem{Text = "Supervisor", Value = ((int)UserTypeEnum.Supervisor).ToString()},
                           new SelectListItem{Text = "Normal", Value = ((int)UserTypeEnum.Normal).ToString()},
                       };
    }
}
遗弃M 2024-09-06 05:31:28

我认为您需要的是如何从用户选择的 CheckBoxList 中收集选定的值,这是我的解决方案:

1-下载 Jquery.json.js 并将其添加到您的视图作为参考:

<script src="../../Scripts/jquery.json.js" type="text/javascript"></script>
2- I've added a ".cssMyClass" to all checkboxlist items so I grab the values by their css class: 


 <script type="text/javascript" >
       $(document).ready(function () {
           $("#btnSubmit").click(sendValues);
         });

         function populateValues()
         {
             var data = new Array();
             $('.myCssClas').each(function () {
                 if ($(this).attr('checked')) {
                     var x = $(this).attr("value");
                     data.push(x);
                 }
             }); 

             return data;
         }

         function sendValues() {
             var data = populateValues();
                   $.ajax({
                       type: 'POST',
                       url: '@Url.Content("~/Home/Save")',
                       data: $.json.encode(data),
                       dataType: 'json',
                       contentType: 'application/json; charset=utf-8',
                       success: function () { alert("1"); }
                   });

           } 



     </script>

3-如您所见,我已添加所有选定的值到一个数组,我已通过 ajax 将其传递给“Home”控制器的“保存”操作
4-在控制器中,您可以通过添加数组作为参数来接收值:

 [HttpPost]
        public ActionResult Save(int[] val)
        {

我搜索了太多,但显然这是唯一的解决方案。如果您找到更好的解决方案,请告诉我。

I think what you need is how gather selected values from CheckBoxList that user selected and here is my solution for that:

1- Download Jquery.json.js and add it to your view as refrence:

<script src="../../Scripts/jquery.json.js" type="text/javascript"></script>
2- I've added a ".cssMyClass" to all checkboxlist items so I grab the values by their css class: 


 <script type="text/javascript" >
       $(document).ready(function () {
           $("#btnSubmit").click(sendValues);
         });

         function populateValues()
         {
             var data = new Array();
             $('.myCssClas').each(function () {
                 if ($(this).attr('checked')) {
                     var x = $(this).attr("value");
                     data.push(x);
                 }
             }); 

             return data;
         }

         function sendValues() {
             var data = populateValues();
                   $.ajax({
                       type: 'POST',
                       url: '@Url.Content("~/Home/Save")',
                       data: $.json.encode(data),
                       dataType: 'json',
                       contentType: 'application/json; charset=utf-8',
                       success: function () { alert("1"); }
                   });

           } 



     </script>

3- As you can see I've added all selected values to an Array and I've passed it to "Save" action of "Home" controller by ajax
4- in Controller you can receive the values by adding an array as argument:

 [HttpPost]
        public ActionResult Save(int[] val)
        {

I've searched too much but apparently this is the only solution. Please let me know if you find a better solution for it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文