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.
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 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(" " + 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>
以前我们做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);
});
});
}
})();