asp.net mvc view 技术汇总

本文介绍ASP.NET MVC中处理CheckBox的方法及jQuery实现CheckBoxList全选与反选功能。探讨了如何在服务器端获取CheckBox状态,以及客户端通过jQuery简化CheckBoxList的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

view 技术的汇总

1.Aspnet mvc Html.Checkbox 处理

This post will explain how to get the value of a checkbox when a form is posted within the world of ASP.NET MVC. This post will explain this approach by first presenting a common problem and then showing you the recommended solution. You can just jump to the solution by clicking here.

The Common Problem

A lot of times, you will ask a user to “sign up” or “register” to access your web application. Sometimes, this process will involve asking a user to agree to the terms of  the site. This task usually relies on the user checking a checkbox stating that they agree to be a nice user. For instance, you can see an example of one such registration page here.

After a user has agreed, and decided to proceed, you should make sure they checked the checkbox on the server side.  The reason for this is to prevent malicious developers from attacking your site. Regardless, if you are using ASP.NET MVC, you may be surprised to learn that getting the value of a checkbox is a little different from what you may be expecting. For instance, imagine you have the following HTML page defined:

<html xmlns=”http://www.w3.org/1999/xhtml” >
  <head><title>Check Test</title></head>
  <body><form action=”/” method=”post”>
    <%= Html.CheckBox(”chkHuman”, false)%> Are you human?<br />
    <input type=”submit” value=”Move Along” />
  </form></body>
</html>

Now imagine that when the user clicks the “Move Along” button, the following action is triggered:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection formValues)
{
  string value = formValues["chkHuman"];
  return View();
}

If the user checks the checkbox, and this action gets executed, you will notice the “value” variable will be set to “true,false”. If the checkbox was not selected, the “value” variable will simply be “false”.  While you could just check the length, or manually parse the value, there is a more elegant solution.

The Solution

The recommended approach would be to write your code as follows:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection formValues)
{
  bool isChecked = false;
  if (Boolean.TryParse(Request.Form.GetValues(”chkHuman”)[0], out isChecked) == false)
    ModelState.AddModelError(”chkHuman”, “Nice try.”);
  return RedirectToAction(”Index”);
}

In this approach, we are relying on the Request.Form object. By indexing the first element of the value returned by the GetValues method, we will get either “true” or “false”. This can then be easily converted to a bool. The fact that the value can easily be converted to a bool is what makes it the recommended approach.

 

2.

Mvc2 Jquery CheckBoxList 实例

HtmlHelper Extensions codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace MvcAppValidate.Extensions
{
    public static class HtmlHelperExtensions
    {
        #region extensions for checkboxlist
        public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IDictionary<string, string> items)
        {

            return CheckBoxList(helper, name, items, null, null);

        }
        public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IDictionary<string, string> items, IDictionary<string, object> checkboxHtmlAttributes)
        {

            return CheckBoxList(helper, name, items, null, checkboxHtmlAttributes);

        }
        public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IDictionary<string, string> items, IEnumerable<string> selectedValues)
        {

            return CheckBoxList(helper, name, items, selectedValues, null);

        }
        public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IDictionary<string, string> items, IEnumerable<string> selectedValues, IDictionary<string, object> checkboxHtmlAttributes)
        {

            var selectListItems = from i in items

                                  select new SelectListItem

                                             {

                                                 Text = i.Key,

                                                 Value = i.Value,

                                                 Selected = (selectedValues != null && selectedValues.Contains(i.Value))

                                             };

            return CheckBoxList(helper, name, selectListItems, checkboxHtmlAttributes);

        }
        public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> items)
        {

            return CheckBoxList(helper, name, items, null);

        }
        public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> items, IDictionary<string, object> checkboxHtmlAttributes)
        {

            var output = new StringBuilder();

            foreach (var item in items)
            {

                output.Append("<div class=/"fields/"><label>");

                var checkboxList = new TagBuilder("input");

                checkboxList.MergeAttribute("type", "checkbox");

                checkboxList.MergeAttribute("name", name);

                checkboxList.MergeAttribute("value", item.Value);

                // Check to see if it’s checked

                if (item.Selected)

                    checkboxList.MergeAttribute("checked", "checked");

                // Add any attributes

                if (checkboxHtmlAttributes != null)

                    checkboxList.MergeAttributes(checkboxHtmlAttributes);

                checkboxList.SetInnerText(item.Text);

                output.Append(checkboxList.ToString(TagRenderMode.SelfClosing));

                output.Append("&nbsp; " + item.Text + "</label></div>");

            }

            return MvcHtmlString.Create(output.ToString());

        }
        #endregion
        #region extensions for CreateHyperLink
        public static MvcHtmlString A(this HtmlHelper helper, string target, string text)
        {
            return MvcHtmlString.Create(String.Format("<a href='{0}'>{1}</a>", target, text));
        }

        #endregion
    }
}

Jquery demo controller codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcAppEntities;
using System.Text;

namespace MvcAppDemoCly.Controllers
{
    public class JqueryDemoController : Controller
    {
        //
        // GET: /JqueryDemo/

        public ActionResult JqueryCheckboxList()
        {
            AjaxWcfService.AjaxEnabledWcfService wcfService = new AjaxWcfService.AjaxEnabledWcfService();
            var userItems = wcfService.GetUsers();
            ViewData["userItems"] = new SelectList(userItems, "ID", "Email");

            return View();
        }

        [HttpPost]
        public string GetCheckedUserIds()
        {
            var checkedUserIds = Request.Form["SelectedUserIds"];
            //ViewData["CheckedUserIds"] = checkedUserIds;
            //return View(@"JqueryCheckboxList");
            return checkedUserIds;
        }

}

View page code:

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

<%@ Import Namespace="MvcAppValidate.Extensions" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    JqueryCheckboxList
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% var users = ViewData["userItems"] as SelectList; %>
    <h2>
        JqueryCheckboxList</h2>
    <% if (ViewData["CheckedUserIds"] != null)
       {%>
    <%: "You had selected UserIds:" + ViewData["CheckedUserIds"]%>
    <%} %>
    <%: Html.CheckBox("chkAll")%><%: Html.Label("secect all/unselect all") %>
    <%using (Html.BeginForm("GetCheckedUserIds", "JqueryDemo", FormMethod.Post))
      { %>
    <% if (users != null)
       { %>
    <%: Html.CheckBoxList("chkUsers", users)%>
    <%} %>
    <%--<input type="submit" value="Submit" />--%>
    <input type="button" value="Submit" onclick="javascript:GetSelectedUserIds();" />
    <%} %>
    <%: Html.A("http://www.163.com","163 com") %>
    <script language="javascript" type="text/javascript">

        $(document).ready(function () {
            $("#chkAll").click(function () {
                //alert($(this).attr("checked"));
                var checked = $(this).attr("checked");
                $("input:checkbox[name='chkUsers']").each(function () {
                    //alert(checked);
                    $(this).attr("checked", checked);
                });
            });

            //$("a").click(ClickATag);
        });
        function GetSelectedUserIds() {
            $.ajax({
                type: "post",
                datatype: "text",
                data: { "SelectedUserIds": GetCheckedValues() },
                url: "/JqueryDemo/GetCheckedUserIds",
                success: function (res) {
                    alert(res);
                }
            });
        }

        function GetCheckedValues() {
            var userIdStr = "";
            //alert($("input:checkbox[name='chkUsers']").length);

            $("input:checkbox[name='chkUsers']").each(function () {
                if ($(this).attr("checked"))
                    userIdStr += $(this).val() + ",";
            });
            userIdStr = userIdStr.substring(0, userIdStr.length - 1);
            return userIdStr;
        }
        //    function ClickATag() {
        //        alert("You are clicking a A tag");
        //    }
    </script>
</asp:Content>

  3.      jquery +做CheckBoxList全选,反选       

以前我们做CheckBoxList全选,反选,一般用Aspx+CodeFile、或者用JavaScript

现在我们可以用JQuery来帮我Easy Choose.

这里我来写三种:

第一种

全选

    $(".checkBoxSelect").each(function() {
                $(this).attr("checked", true); 
     });

反选

     $(".checkBoxSelect").each(function() {
                        if($(this).attr("checked"))
                        {
                                $(this).attr("checked", false);
                        }
                        else
                        {
                                $(this).attr("checked", true);
                        }
                });

第二种

全选

    $("#<%=CheckBoxList.ClientID %> input:checkbox").each(function(index,domEle){               if(this.type=="checkbox")                   this.checked=true;    });反选     $("#<%=CheckBoxList.ClientID %> input:checkbox").each(function(index,domEle){              if(this.type=="checkbox")                  this.checked=!this.checked;    });第三种     使用toggle方式进行全选、反选           btnSelAll.click(function() {
               jqClass.toggleChecks(null);
           });

           var jqClass= {
                 //Toggle Item For CheckBoxList
                 toggleChecks: function(b) {
                          $("#<%=cblContact.ClientID %> input[type=checkbox]").each(function() {
                                    if (typeof this.checked != "undefined") {
                                              if (b == null)
                                                    this.checked = (!this.checked);
                                              else
                                                    this.checked = b;
                                     }
                            });
              }
       }

第四种:Plugin 方式

(function($$) {
    $.fn.jCheckboxList = function(opt) {
        var option = {
            root: '',  //  checkbox id of "select all"
            childCls: ''  // another checkboxs
        };
        var opt = $.extend({}, option, opt);
        var el = $(this).attr('id');
        var allchild = "#" + el + " :input[type=checkbox]." + opt.childCls;
        $("#" + opt.root).click(function() {
            var isChecked = $(this).attr('checked');
            if (isChecked)
                $(allchild).attr('checked', true);
            else
                $(allchild).attr('checked', false);
        });

        $.each($(allchild), function(i, v) {
            var all = $(allchild).length;
            $(v).click(function() {
                var count = $(allchild + "[checked]").length;
                if (count == all)
                    $("#" + opt.root).attr('checked', true);
                else
                    $("#" + opt.root).attr('checked', false);
            });
        });
    }
})();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

似水流年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值