ASP.NET MVC Preview 5 演示Demo #7 实现JQuery表单数据验证及JQuery操作Html元素
ASP.NET MVC Preview 5 演示Demo系列: http://mike108mvp.cnblogs.com
ASP.NET MVC [QQ交流群1]:47788243 [QQ交流群2]:1214648 [QQ交流群3]:1215279
JQuery is a lightweight javascript library adding the Ajax and other functionality to a web application. Recently Microsoft has announced that they will integrate JQuery into their Visual Studio IDE. The next version of ASP.NET MVC will be the first product shipped with JQuery.
This Mvc Demo #7 demonstrates how to use JQuery to validate the submit form data and how to use JQuery to manipulate Html elements.
Hope this helps, let's get started.
Download the Code:https://files.cnblogs.com/mike108mvp/Mike108Demo07.rar
这个演示项目实现了在ASP.NET MVC中使用开源Javasript脚本库 JQuery来实现表单数据验证及操作Html元素(动态隐藏/显示一个采购数量输入框)。
开发环境:Visual Studio 2008 SP1 + ASP.NET MVC Preview 5 + Linq To Sql + SQL Server 2005
ASP.NET MVC Preview 5 下载地址: http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16775
【Step By Step 操作步骤】
1、下载本演示源码:https://files.cnblogs.com/mike108mvp/Mike108Demo07.rar 【ok】
2、打开下载的源码中的“数据库脚本Demo07.sql”脚本文件,双击,在SQL Server 2005 中执行。该Sql脚本将生成一个新的mike108mvp数据库,里面包含5个表User、UserType、Product、Order、OrderItem。【ok】
3、Visual Studio 2008 双击打开下载的演示源码中的 Mike108Demo.sln 解决方案文件,按F5运行。【ok】
4、运行后,点击页面右上角的“采购”链接。打钩选中要采购的产品,将动态显示出“采购数量”输入框,在里面输入非数字时,点击“批量采购”就会激活JQuery数据验证。【ok】
5、点击订单列表中的“订单明细”链接,可以在右边显示该订单的明细列表。【ok】
6、母版页site.master添加JQuery引用。【ok】
<script src="/Content/jquery/jquery-1.2.6.pack.js" type="text/javascript"></script>
<link href="/Content/jquery/style/validator.css" type="text/css" rel="stylesheet" />
<script src="/Content/jquery/formValidatorRegex.js" type="text/javascript"></script>
<script src="/Content/jquery/formValidator.js" type="text/javascript"></script>
7、UsersController.cs 【ok】
public class UsersController : Controller
{
Mike108mvpDataContext db = new Mike108mvpDataContext();
Demo #1 CRUD操作#region Demo #1 CRUD操作
public ActionResult UserAdd()
{
return View(@"Add");
}
public ActionResult UserCreate()
{
if (Request.HttpMethod != "POST")
{ return View(@"Add"); }
User model = new User();
UpdateModel(model, Request.Form.AllKeys);
db.Users.InsertOnSubmit(model);
db.SubmitChanges();
return RedirectToAction("UserList");
}
public ActionResult UserEdit(int userId)
{
User model = db.Users.FirstOrDefault(e => e.UserId == userId);
return View(@"Edit", model);
}
public ActionResult UserUpdate(int userId)
{
if (Request.HttpMethod != "POST")
{ return RedirectToAction("UserEdit", new { userId = userId }); }
User model = db.Users.FirstOrDefault(e => e.UserId == userId);
UpdateModel(model, Request.Form.AllKeys);
db.SubmitChanges();
return RedirectToAction("UserList");
}
public ActionResult UserDetail(int userId)
{
User model = db.Users.FirstOrDefault(e => e.UserId == userId);
return View(@"Detail", model);
}
public ActionResult UserDelete(int userId)
{
User model = db.Users.FirstOrDefault(e => e.UserId == userId);
db.Users.DeleteOnSubmit(model);
db.SubmitChanges();
return RedirectToAction("UserList");
}
public ActionResult UserList1()
{
if (db.Users.Count() == 0 || db.UserTypes.Count() == 0)
{
return RedirectToAction("DataReset");
}
ViewData["UserList"] = db.Users.ToList();
return View(@"List");
}
#endregion
Demo #1 数据重置#region Demo #1 数据重置
public ActionResult DataReset()
{
//批量添加用户分类
if (db.UserTypes.Count() == 0)
{
List<UserType> userTypelist = new List<UserType>
{
new UserType { TypeId=1, TypeName = "总统" },
new UserType { TypeId=2, TypeName = "独裁者" },
new UserType { TypeId=3, TypeName = "S.H.E" },
new UserType { TypeId=4, TypeName = "小虎队" },
new UserType { TypeId=5, TypeName = "NBA" },
new UserType { TypeId=6, TypeName = "科学家" }
};
db.UserTypes.InsertAllOnSubmit(userTypelist);
db.SubmitChanges();
}
//批量删除用户
//List<User> oldList = db.Users.ToList();
//db.Users.DeleteAllOnSubmit(oldList);
//批量添加用户
if (db.Users.Count() == 0)
{
List<User> userlist = new List<User>
{
new User { UserName = "孙中山", TypeId=1, Sex=true, Age = 53, Career = "中国总统" },
new User { UserName = "蒋中正", TypeId=1, Sex=true, Age = 36, Career = "中国总统" },
new User { UserName = "小布什", TypeId=1, Sex=true, Age = 61, Career = "美国总统" },
new User { UserName = "列宁", TypeId=2, Sex=true, Age = 49, Career = "邪恶苏联" },
new User { UserName = "斯大林", TypeId=2, Sex=true, Age = 49, Career = "邪恶苏联" },
new User { UserName = "Selina", TypeId=3, Sex=false, Age = 26, Career = "女艺人" },
new User { UserName = "Hebe", TypeId=3, Sex=false, Age = 25, Career = "女艺人" },
new User { UserName = "Ella", TypeId=3, Sex=false, Age = 26, Career = "女艺人" },
new User { UserName = "吴奇隆", TypeId=4, Sex=true, Age = 34, Career = "男艺人" },
new User { UserName = "苏有朋", TypeId=4, Sex=true, Age = 33, Career = "男艺人" },
new User { UserName = "陈志朋", TypeId=4, Sex=true, Age = 35, Career = "男艺人" },
new User { UserName = "乔丹", TypeId=5, Sex=true, Age = 39, Career = "球星" },
new User { UserName = "皮蓬", TypeId=5, Sex=true, Age = 38, Career = "球星" },
new User { UserName = "罗德曼", TypeId=5, Sex=true, Age = 37, Career = "球星" },
new User { UserName = "姚明", TypeId=5, Sex=true, Age = 27, Career = "球星" },
new User { UserName = "易建联", TypeId=5, Sex=true, Age = 20, Career = "球星" },
new User { UserName = "科比", TypeId=5, Sex=true, Age = 29, Career = "球星" },
new User { UserName = "麦蒂", TypeId=5, Sex=true, Age = 33, Career = "球星" },
new User { UserName = "艾弗森", TypeId=5, Sex=true, Age = 29, Career = "球星" },
new User { UserName = "詹姆斯", TypeId=5, Sex=true, Age = 29, Career = "球星" },
new User { UserName = "加内特", TypeId=5, Sex=true, Age = 32, Career = "球星" },
new User { UserName = "比尔盖茨", TypeId=6, Sex=true, Age = 62, Career = "微软老大" },
new User { UserName = "Scott Guthrie", TypeId=6, Sex=true, Age = 33, Career = "ASP.NET Leader" }
};
db.Users.InsertAllOnSubmit(userlist);
db.SubmitChanges();
}
//批量添加产品
if (db.Products.Count() == 0)
{
List<Product> productlist = new List<Product>
{
new Product { ProductName="苹果", Price=(decimal)1.5 },
new Product { ProductName="梨子", Price=(decimal)2.0 },
new Product { ProductName="柑橘", Price=(decimal)0.5 },
new Product { ProductName="荔枝", Price=(decimal)1.8 },
new Product { ProductName="菠萝", Price=(decimal)3.0 },
new Product { ProductName="草莓", Price=(decimal)3.5 },
new Product { ProductName="樱桃", Price=(decimal)6.0 },
new Product { ProductName="橄榄", Price=(decimal)8.5 },
new Product { ProductName="芒果", Price=(decimal)9.0 }
};
db.Products.InsertAllOnSubmit(productlist);
db.SubmitChanges();
}
return RedirectToAction("UserList");
}
#endregion
Demo #2 微软Membership权限#region Demo #2 微软Membership权限
[Authorize] //登陆后才能查看
public ActionResult UserMembership()
{
User model = db.Users.FirstOrDefault(e => e.UserName == "孙中山");
return View(@"Detail", model);
}
#endregion
Demo #3 实现MVC批量上传文件#region Demo #3 实现MVC批量上传文件
public ActionResult Upload()
{
return View(@"Upload");
}
public ActionResult UploadFiles()
{
var r = new List<MikeUploadFile>();
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "Upload\\", Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
r.Add(new MikeUploadFile()
{
Name = savedFileName,
Length = hpf.ContentLength
});
}
return View(@"Upload", r);
}
#endregion
Demo #4 实现RadioButtonList和DropDownList应用#region Demo #4 实现RadioButtonList和DropDownList应用
// Demo #4 没有添加新的Controller代码
#endregion
Demo #5 实现MikePager数据分页和GridView控件#region Demo #5 实现MikePager数据分页和GridView控件
public ActionResult UserList(int? pageIndex, int? pageSize)
{
if (db.Users.Count() == 0 || db.UserTypes.Count() == 0)
{
return RedirectToAction("DataReset");
}
int pIndex = pageIndex ?? 1;
int pSize = pageSize ?? 10;
GridViewData<User> gridViewData = new GridViewData<User>();
gridViewData.PagedList = db.Users.OrderBy(e => e.UserId).ToPagedList<User>(pIndex, pSize);
return View(@"List", gridViewData);
}
#endregion
Demo #6 实现MvcContrib的Html.CheckBoxList应用#region Demo #6 实现MvcContrib的Html.CheckBoxList应用
[AcceptVerbs("GET")]
public ActionResult BuyProduct()
{
List<Product> productList = db.Products.ToList();
ViewData["products"] = productList;
return View(@"BuyProduct");
}
[AcceptVerbs("Post")]
public ActionResult BuyProductSave()
{
string[] selectedList = Request.Form.GetValues("productList"); //被选中的项
int selectedAmount = Request.Form.GetValues("productList").Length; //被选中项的个数
string checkBoxValueList = Request.Form["productList"]; //得到选中的多个CheckBox值,例如 1,2,5
//本次订单的产品Id列表,用逗号隔开保存在Order表的ProductList字段中
string buyProductIds = "";
StringBuilder sb = new StringBuilder();
foreach (string productId in selectedList)
{
sb.Append(productId + ",");
}
if (sb.Length > 1)
{
buyProductIds = sb.ToString(0, sb.Length - 1);
}
//假设当前登陆用户是Selina
User currentUser = db.Users.FirstOrDefault(e => e.UserName == "Selina");
//添加一个订单到Order表
Order order = new Order();
order.OrderName = currentUser.UserName + " 订单";
order.OrderTime = DateTime.Now;
order.UserId = currentUser.UserId;
order.ProductList = buyProductIds; //成功
//order.ProductList = checkBoxValueList; //成功
db.Orders.InsertOnSubmit(order);
db.SubmitChanges();
//批量添加多个订单明细到OrderItem表
foreach (string productId in selectedList)
{
OrderItem orderItem = new OrderItem();
orderItem.OrderId = order.OrderId;
orderItem.UserId = currentUser.UserId;
orderItem.ProductId = int.Parse(productId);
int quantity = int.Parse(Request.Form["Quantity" + productId]); //采购数量
orderItem.Quantity = quantity;
Product product = db.Products.FirstOrDefault(e => e.ProductId == int.Parse(productId));
orderItem.UnitPrice = product.Price.Value;
db.OrderItems.InsertOnSubmit(orderItem);
}
db.SubmitChanges();
return RedirectToAction("OrderList");
}
public ActionResult OrderList(int? pageIndex, int? pageSize, int? orderId)
{
int pIndex = pageIndex ?? 1;
int pSize = pageSize ?? 10;
//订单列表
GridViewData<Order> gridViewData = new GridViewData<Order>();
gridViewData.PagedList = db.Orders.OrderByDescending(e => e.OrderId).ToPagedList(pIndex, pSize);
//订单明细列表
GridViewData<OrderItem> orderItemGridViewData = new GridViewData<OrderItem>();
if (!string.IsNullOrEmpty(Request.QueryString["orderId"]))
{
int id = int.Parse(Request.QueryString["orderId"]);
orderItemGridViewData.PagedList = db.OrderItems.Where(e => e.OrderId == id).OrderBy(e => e.OrderItemId).ToPagedList(pIndex, pSize);
}
else
{
orderItemGridViewData.PagedList = db.OrderItems.OrderBy(e => e.OrderItemId).ToPagedList(pIndex, 100);
}
ViewData["OrderItemList"] = orderItemGridViewData;
return View(@"~/Views/Users/OrderList.aspx", gridViewData);
}
#endregion
Demo #7 实现JQuery表单数据验证及JQuery操作Html元素#region Demo #7 实现JQuery表单数据验证及JQuery操作Html元素
// Demo #7 没有添加新的Controller代码
#endregion
}
8、Views/Users/BuyProduct.aspx 产品采购页面,Views/Users/OrderList.aspx 订单列表与订单明细页面。【ok】
JQuery代码
<script type="text/javascript">
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var i = $(this);
var r = parseInt(i.attr("id").replace("MikeCheckbox", "")) + 0;
if (this.checked) {
$("#Quantity" + r).css("display", "inline");
} else {
$("#Quantity" + r).hide();
$("#Quantity" + r + "Tip").hide();
}
});
$.formValidator.initConfig({ formid: "mikeForm", onerror: function() {
$("input[type=checkbox]").each(function() {
if (!this.checked) {
var i = $(this);
var r = parseInt(i.attr("id").replace("MikeCheckbox", "")) + 0;
$("#Quantity" + r + "Tip").hide();
}
});
alert("数据验证没有通过!请看页面中的错误提示!");
}
});
$(".lily > input[type=text]").formValidator({ onshow: "", onfocus: "请输入正整数", oncorrect: "正确" }).regexValidator({ regexp: "MoreZeroInt", datatype: "enum", onerror: "格式不对!只能输入大于0的整数!" });
});
</script>
Download the Code:https://files.cnblogs.com/mike108mvp/Mike108Demo07.rar
ASP.NET MVC Preview 5 演示Demo系列: http://mike108mvp.cnblogs.com
Demo #1 实现CRUD增删查改:http://www.cnblogs.com/mike108mvp/archive/2008/08/31/1280689.html
Demo #2 实现Membership角色权限控制:http://www.cnblogs.com/mike108mvp/archive/2008/09/03/1283432.html
Demo #3 实现MVC批量上传文件:http://www.cnblogs.com/mike108mvp/archive/2008/09/04/1284087.html
Demo #4 实现RadioButtonList与DropDownList应用:http://www.cnblogs.com/mike108mvp/archive/2008/09/15/1291153.html
Demo #5 实现MikePager数据分页和GridView控件:http://www.cnblogs.com/mike108mvp/archive/2008/09/19/1294079.html
Demo #6 实现MvcContrib的Html.CheckBoxList()应用:http://www.cnblogs.com/mike108mvp/archive/2008/09/27/1300572.html