第6章 ASP.NET(模型验证)
、任务:实现图书到数据库
1、 验证
2、 保存
重点:基本验证、数据获取和保存,自定义客户端验证
一、 基本的模型验证
A、 模型验证:确保接受的数据适合绑定到model的过程
B、 功能包括:
1、 检查接受的数据
2、 帮助用户修正问题(提示)
二、 使用另外一种验证技术
三、 客户端验证
四、 执行远程验证
结合第五章内容,实现体育产品后台添加,修改功能
一、在“Models”文件添加一个类名为“SportModel”并编辑后台添加控件属性
1、如图所示(上部分)
2、如图所示(下部分)
代码示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations; namespace MvcProduct.Models { //产品体育 public class SportModel { [HiddenInput(DisplayValue = false)] public int Id { get; set; } //书名 [Display(Name = "名 称:")] [Required(ErrorMessage = "书名不能为空")] [StringLength(maximumLength: 100, ErrorMessage = "书名不能太长")] public string Title { get; set; } //价格 [Display(Name = "价 格:")] [Required(ErrorMessage = "价格不能为空")] [Range(minimum: 0.01, maximum: double.MaxValue, ErrorMessage = "价格超出范围")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:F2}")] public decimal Price { get; set; } //简介 [Display(Name = "简 介:")] [Required(ErrorMessage = "简介不能为空")] public string NCount { get; set; } [Display(Name = "分类:")] public string CategorId { get; set; } [Display(Name = "图片:")] public string ImgSrc { get; set; } } }
二、在“LinqService/Product.edmx” 里单击右键添加“从数据库更新模型”添加一个分类表
1、如图所示(从数据库更新模型):
2、如图所示(下一步)
3、如图所示(登入)
4、如图所示(选择否)
5、如图所示(选择表,确定)
三、完成后,在“LinBLL/ProductBll.cs”编辑分类方法
如图所示:
代码示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LinqService; //引用 namespace LinqBLL { public class ProductBll { public List<Product> GetProduct() { using (SportsStoreEntities se = new SportsStoreEntities()) { var products = se.Product; //数据库里面表名称 return products.ToList(); } } //通过分类名获取体育产品列表 public List<Product> GetProductByCateName(string cate,int stIndex,int count) { using(SportsStoreEntities se=new SportsStoreEntities()) { if (string.IsNullOrEmpty(cate)) //查找所有 { var products=se.Product.OrderBy(x=>x.ProductID).Skip(stIndex).Take(count); return products.ToList(); } else //查找对应分类数据 { var books = from a in se.Product where a.Category.Contains(cate) select a; return books.OrderBy(x=>x.ProductID).Skip(stIndex).Take(count).ToList(); } } } //获取所有记录数 public int GetRecordCount(string cate) { using (SportsStoreEntities se = new SportsStoreEntities()) { if (string.IsNullOrEmpty(cate)) //查找所有 { return se.Product.Count(); } else //查找对应分类数据 { var books = from a in se.Product where a.Category.Contains(cate) select a; return books.Count(); } } } //获取分类名称集 public IEnumerable<string> GetCategories() { var se = new SportsStoreEntities(); var s = from a in se.Product select new { a.Category }; //Distinct:去掉重复分类名,OrderBy:升序 return s.Select(x => x.Category).Distinct().OrderBy(x => x); } //删除方法 public bool Delete(int id) { bool b = true; using (var st = new SportsStoreEntities()) { try { var product = st.Product.SingleOrDefault(a => a.ProductID == id); st.Product.Remove(product); st.SaveChanges(); } catch { b = false; } return b; } } //信息详细 public Product GetModel(int id) { using (SportsStoreEntities st = new SportsStoreEntities()) { Product model = st.Product.SingleOrDefault(a => a.ProductID == id); return model; } } //信息查询 public Product GetProductById(int id) { using (var st = new SportsStoreEntities()) { Product pro = st.Product.SingleOrDefault(a => a.ProductID == id); return pro; } } // 获取分类集 public List<Categories> GetCates() { using (var st = new SportsStoreEntities()) { var s = from a in st.Categories select a; return s.ToList<Categories>(); } } } }
四、到“Areas/Areas/Controllers/StoreController.cs”调用方法
1、如图所示(下部分调用代码):
2、如图所示(上部分调用代码):
代码示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcProduct.Models; using LinqService; using LinqBLL; namespace MvcProduct.Areas.Areas.Controllers { public class StoreController : Controller { ProductBll bll = new ProductBll(); //选中列表项集合 List<SelectListItem> items = new List<SelectListItem>(); public StoreController() { AddCates(); } // // GET: /Areas/Store/ public ActionResult Index() { return View(); } public ActionResult List() { IEnumerable<Product> products = bll.GetProduct(); return View(products); } //删除 public ActionResult Delete(int id) { bll.Delete(id); return RedirectToAction("List", "Store"); } //信息详细 public ActionResult GetModel(int id) { return View(bll.GetModel(id)); } //添加分类 public void AddCates() { List<Categories> lst = bll.GetCates(); foreach (Categories cate in lst) { items.Add(new SelectListItem { Value = cate.Id.ToString(), Text = cate.Name }); } } //创建(视图) public ActionResult Create() { ViewBag.Cates = items; return View(); } [HttpPost] public ActionResult Create(SportModel sm) { return View(sm); } } }
五、继续到“Areas/Areas/Controllers/StoreController.cs”类里面找到“Create”方法"添加视图"并选择相关属性
如图所示;
六、找到分类名称,修改分类
如图所示:
代码示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@model MvcProduct.Models.SportModel @{ ViewBag.Title = "添加体育产品"; Layout = "~/Areas/Areas/Views/Shared/_Layout.cshtml"; } <h2>Create</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>SportModel</legend> <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.Price) </div> <div class="editor-field"> @Html.EditorFor(model => model.Price) @Html.ValidationMessageFor(model => model.Price) </div> <div class="editor-label"> @Html.LabelFor(model => model.NCount) </div> <div class="editor-field"> @Html.EditorFor(model => model.NCount) @Html.ValidationMessageFor(model => model.NCount) </div> <div class="editor-label"> @Html.LabelFor(model => model.CategorId) </div> <div class="editor-field"> @Html.DropDownListFor(model => model.CategorId, ViewBag.Cates as List<SelectListItem>) </div> <div class="editor-label"> @Html.LabelFor(model => model.ImgSrc) </div> <div class="editor-field"> @Html.EditorFor(model => model.ImgSrc) @Html.ValidationMessageFor(model => model.ImgSrc) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Store", "List") </div>
注意:创建模板名称要与“Areas/Areas/Views/List.cshtml"里体育产品一样
如图所示:
运行效果:
七、这里只是实现分类数据加载,要添加还要继续完善,继续到“Areas/Areas/Views/List.cshtml"完善模板代码,
添加数据与修改模板代码
1、如图所示(添加一行语句)
2、如图所示(修改两个字符代码)
代码示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@model MvcProduct.Models.SportModel @{ ViewBag.Title = "添加体育产品"; Layout = "~/Areas/Areas/Views/Shared/_Layout.cshtml"; } <h2>新增功能</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm("Create", "Store", FormMethod.Post, new { enctype = "multipart/form-data"})) { @Html.ValidationSummary(true) <fieldset> <legend>SportModel</legend> <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.Price) </div> <div class="editor-field"> @Html.EditorFor(model => model.Price) @Html.ValidationMessageFor(model => model.Price) </div> <div class="editor-label"> @Html.LabelFor(model => model.CategorId) </div> <div class="editor-field"> @Html.DropDownListFor(model => model.CategorId, ViewBag.Cates as List<SelectListItem>) </div> <div class="editor-label"> @Html.LabelFor(model => model.NCount) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.NCount, new {style="width:310px" }) @Html.ValidationMessageFor(model => model.NCount) </div> <div class="editor-label"> @Html.LabelFor(model => model.ImgSrc) </div> <div class="editor-field"> <input type="file" id="ImgSrc" name="ImgSrc" /> </div> <p> <input type="submit" value="保存" /> </p> </fieldset> } <div> @Html.ActionLink("返回", "List") </div>
八、到“ProductBll.cs”类编辑添加方法和修改方法
1、如图所示(添加方法)
2、如图所示(修改方法)
代码示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LinqService; //引用 namespace LinqBLL { public class ProductBll { public List<Product> GetProduct() { using (SportsStoreEntities se = new SportsStoreEntities()) { var products = se.Product; //数据库里面表名称 return products.ToList(); } } //通过分类名获取体育产品列表 public List<Product> GetProductByCateName(string cate,int stIndex,int count) { using(SportsStoreEntities se=new SportsStoreEntities()) { if (string.IsNullOrEmpty(cate)) //查找所有 { var products=se.Product.OrderBy(x=>x.ProductID).Skip(stIndex).Take(count); return products.ToList(); } else //查找对应分类数据 { var books = from a in se.Product where a.Category.Contains(cate) select a; return books.OrderBy(x=>x.ProductID).Skip(stIndex).Take(count).ToList(); } } } //获取所有记录数 public int GetRecordCount(string cate) { using (SportsStoreEntities se = new SportsStoreEntities()) { if (string.IsNullOrEmpty(cate)) //查找所有 { return se.Product.Count(); } else //查找对应分类数据 { var books = from a in se.Product where a.Category.Contains(cate) select a; return books.Count(); } } } //获取分类名称集 public IEnumerable<string> GetCategories() { var se = new SportsStoreEntities(); var s = from a in se.Product select new { a.Category }; //Distinct:去掉重复分类名,OrderBy:升序 return s.Select(x => x.Category).Distinct().OrderBy(x => x); } //删除方法 public bool Delete(int id) { bool b = true; using (var st = new SportsStoreEntities()) { try { var product = st.Product.SingleOrDefault(a => a.ProductID == id); st.Product.Remove(product); st.SaveChanges(); } catch { b = false; } return b; } } //信息详细 public Product GetModel(int id) { using (SportsStoreEntities st = new SportsStoreEntities()) { Product model = st.Product.SingleOrDefault(a => a.ProductID == id); return model; } } //信息查询 public Product GetProductById(int id) { using (var st = new SportsStoreEntities()) { Product pro = st.Product.SingleOrDefault(a => a.ProductID == id); return pro; } } // 获取分类集 public List<Categories> GetCates() { using (var st = new SportsStoreEntities()) { var s = from a in st.Categories select a; return s.ToList<Categories>(); } } //新增产品 public bool Add(Product model) { bool b = false; using (var st = new SportsStoreEntities()) { try { st.Product.Add(model); st.SaveChanges(); b = true; } catch { } } return b; } //修改产品 public bool Update(Product model) { bool b = false; using (var st = new SportsStoreEntities()) { try { Product info = st.Product.SingleOrDefault(a => a.ProductID == model.ProductID); info.Name = model.Name; info.Price = model.Price; info.nDescription = model.nDescription; info.Image = model.Image; info.Category = model.Category; info = model; st.SaveChanges(); b = true; } catch { } } return b; } } }
九、完成后,到“Areas/Areas/Controllers/StoreController.cs”调用放方法与修改
1、如图所示(添加方法调用)
2、如图所示(修改方法调用)
注意:修改添加分类名称,否则会以数字编号显示出来
代码示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcProduct.Models; using LinqService; using LinqBLL; namespace MvcProduct.Areas.Areas.Controllers { public class StoreController : Controller { ProductBll bll = new ProductBll(); //选中列表项集合 List<SelectListItem> items = new List<SelectListItem>(); public StoreController() { AddCates(); } // // GET: /Areas/Store/ public ActionResult Index() { return View(); } public ActionResult List() { IEnumerable<Product> products = bll.GetProduct(); return View(products); } //删除 public ActionResult Delete(int id) { bll.Delete(id); return RedirectToAction("List", "Store"); } //信息详细 public ActionResult GetModel(int id) { return View(bll.GetModel(id)); } //添加分类 public void AddCates() { List<Categories> lst = bll.GetCates(); foreach (Categories cate in lst) { items.Add(new SelectListItem { Value = cate.Name.ToString(), Text = cate.Name }); } } //创建(视图) public ActionResult Create() { ViewBag.Cates = items; return View(); } //创建提交 [HttpPost] public ActionResult Create(SportModel sm,HttpPostedFileBase Imgsrc) { if (ModelState.IsValid) { Product info = new Product(); info.Name = sm.Title; info.Price = sm.Price; info.nDescription = sm.NCount; info.Category = sm.CategorId; info.Image = ""; //上传图片 if (!string.IsNullOrEmpty(Imgsrc.FileName)) { string path = Server.MapPath("~/Image/"); string filename = DateTime.Now.ToString("yyyMMddhhmmss") + ".jpg"; Imgsrc.SaveAs(path + filename); info.Image = "Image/" + filename; } bll.Add(info); } ViewBag.Cates = items; return View(sm); } //编辑图书 public ActionResult Edit(int id) { ViewBag.Cates = items; //分类数据 //赋值 Product info = bll.GetProductById(id); SportModel model= new SportModel(); model.Title = info.Name; model.Price = info.Price; model.NCount = info.nDescription; model.CategorId = info.Category; model.ImgSrc = info.Image; return View(model); } //编辑图片 [HttpPost] public ActionResult Edit(SportModel model, HttpPostedFileBase Imgsrc) { Product info = bll.GetProductById(model.Id); info.Name = model.Title; info.Price = model.Price; info.nDescription = model.NCount; info.Category = model.CategorId; info.Image = model.ImgSrc; //上传图片 if (!string.IsNullOrEmpty(Imgsrc.FileName)) { string path = Server.MapPath("~/Image/"); string filename = DateTime.Now.ToString("yyyMMddhhmmss") + ".jpg"; Imgsrc.SaveAs(path + filename); info.Image = "Image/" + filename; } bll.Update(info); ViewBag.Cates = items; //分类数据 return View(model); } } }
十、继续到“Areas/Areas/Controllers/StoreController.cs”找到“Edit”方法”添加视图“,选择相应名称
如图所示:
十一、找到“Areas/Areas/Views/Store/Create.cshtml”模板代码复制到“Edit.cshtml”修改些代码即可
1、如图所示(上部分):
2、如图所示(下部分):
代码示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@model MvcProduct.Models.SportModel @{ ViewBag.Title = "修改"; Layout = "~/Areas/Areas/Views/Shared/_Layout.cshtml"; } <h2>修改</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm("Edit", "Store", FormMethod.Post, new { enctype = "multipart/form-data"})) { @Html.ValidationSummary(true) <fieldset> <legend>SportModel</legend> <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.Price) </div> <div class="editor-field"> @Html.EditorFor(model => model.Price) @Html.ValidationMessageFor(model => model.Price) </div> <div class="editor-label"> @Html.LabelFor(model => model.CategorId) </div> <div class="editor-field"> @Html.DropDownListFor(model => model.CategorId, ViewBag.Cates as List<SelectListItem>) </div> <div class="editor-label"> @Html.LabelFor(model => model.NCount) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.NCount, new {style="width:310px" }) @Html.ValidationMessageFor(model => model.NCount) </div> <div class="editor-label"> @Html.LabelFor(model => model.ImgSrc) </div> <div class="editor-field"> <input type="file" id="ImgSrc" name="ImgSrc" /> </div> <div class="editor-field"> <img src="../../../@Model.ImgSrc" /> </div> <p> <input type="submit" value="保存" /> </p> </fieldset> } <div> @Html.ActionLink("返回上一级", "List") </div>
运行效果: