ASP.NET MVC Preview 5 演示Demo #8 实现JQuery结合Json进行后台数据Ajax方式验证
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 #8 demonstrates how to use JQuery and Json to validate the submit form data in an Ajax way.
Hope this helps, let's get started.
Download the Code:https://files.cnblogs.com/mike108mvp/Mike108Demo08.rar
该项目演示了在ASP.NET MVC中使用开源Javasript脚本库JQuery结合Json进行后台数据Ajax方式验证。
开发环境: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/Mike108Demo08.rar 【ok】
2、打开下载的源码中的“数据库脚本Demo08.sql”脚本文件,双击,在SQL Server 2005 中执行。该Sql脚本将生成一个新的mike108mvp数据库,里面包含5个表User、UserType、Product、Order、OrderItem。【ok】
3、Visual Studio 2008 双击打开下载的演示源码中的 Mike108Demo.sln 解决方案文件,按F5运行。【ok】
4、运行后,点击页面右上角的“添加”链接。输入姓名,将采用Ajax方式实时验证姓名是否已存在。由JQuery调用Url.Action("IsExistUser") 返回一个Json数据,判断是否已经存在该用户名。
5、Views/Users/Add.aspx 【ok】
JQuery验证代码
<script type="text/javascript">
$(function() {
$.formValidator.initConfig({ formid: "mikeForm", onerror: function() { alert("数据验证没有通过!请看页面中的错误提示!") } });
$("input:radio[name='sex']").formValidator({ tipid: "sexTip", onshow: "请选择性别", onfocus: "请选择!", oncorrect: "正确" }).inputValidator({ min: 1, max: 1, onerror: "请选择性别!" });
$("#TypeId").formValidator({ onshow: "", onfocus: "", oncorrect: "正确" }).inputValidator({ min: 1, onerror: "请选择!" });
$("#Age").formValidator({ onshow: "请输入正整数", onfocus: "请输入正整数", oncorrect: "正确" }).inputValidator({ min: 1, max: 5, onerror: "请输入" }).regexValidator({ regexp: "MoreZeroInt", datatype: "enum", onerror: "只能输入大于0的整数!" });
$("#Career").formValidator({ onshow: "请输入", onfocus: "至少2个字符,最多5个字符", oncorrect: "正确" }).inputValidator({ min: 2, max: 5, onerror: "请输入职业(至少2个字符,最多5个字符)" });
var valurl = '<%=Url.Action("IsExistUser") %>';
$("#UserName").formValidator({ onshow: "请输入用户名", onfocus: "用户名至少1个字符,最多64个字符", oncorrect: "恭喜!该用户名可以注册" }).inputValidator({ min: 1, max: 64, onerror: "请输入用户名(至少1个字符,最多64个字符)" })
.ajaxValidator({
type: "get",
url: valurl,
datatype: "json",
success: function(data) {
if (data == "0") {
return true;
}
else {
return false;
}
},
buttons: $("#submitButtonId"),
error: function() { alert("服务器没有返回数据,可能服务器忙,请重试"); },
onerror: "用户名已存在,请更换用户名",
onwait: "正在对用户名进行合法性校验,请稍候"
});
});
</script>
6、运行后,点击页面右上角的“采购”链接。打钩选中要采购的产品,用JQuery控制必须选中几个产品。本Demo演示的是必须选中产品个数为2个或者3个。【ok】
7、Views/Users/BuyProduct.aspx 产品采购页面【ok】
Code
$("input:checkbox[@name='productList']").formValidator({ tipid: "CheckTip", onshow: "请选择要采购的产品(至少选择2个,最多选择3个)", onfocus: "请选择要采购的产品(至少选择2个,最多选择3个)", oncorrect: "选择产品个数正确" }).inputValidator({ min: 2, max: 3, onerror: "你选的产品个数不对(至少选择2个,最多选择3个)" });
8、母版页site.master添加JQuery引用。【ok】
9、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
Demo #8 实现JQuery结合Json进行后台数据Ajax方式验证#region Demo #8 实现JQuery结合Json进行后台数据Ajax方式验证
public ActionResult IsExistUser(string userName)
{
if (db.Users.FirstOrDefault(e=>e.UserName == userName) != null)
{
return Json(1); //用户名已存在
}
else
{
return Json(0);
}
}
#endregion
}
Download the Code:https://files.cnblogs.com/mike108mvp/Mike108Demo08.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
Demo #7 实现JQuery表单数据验证及JQuery操作Html元素:http://www.cnblogs.com/mike108mvp/archive/2008/10/05/1304337.html