效果图
实现过程
控制器代码
cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index(bool PriceOrderDese=false)
{
ViewData["goods"] = BLL.GoodsManger.Show();
ViewData["sum"] = BLL.GoodsManger.Sun();
ViewData["goods"] = BLL.GoodsManger.getGoodlist(PriceOrderDese);
ViewBag.PriceOrderDese = !PriceOrderDese;
return View();
}
public ActionResult DeleteGood(string goodId) {
BLL.GoodsManger.Delect(goodId);
return RedirectToAction("Index");
}
public ActionResult AddGood()
{
return View();
}
[HttpPost]
public ActionResult AddGood(Goods good)
{
//获取表单验证状态
if (ModelState.IsValid)
{
if (BLL.GoodsManger.AddGood(good))
{
return RedirectToAction("Index");
}
else
{
return View();
}
}
else
{
ViewBag.Good = good;
return View();
}
}
}
}
models 代码
cs
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码是根据模板生成的。
//
// 手动更改此文件可能会导致应用程序中发生异常行为。
// 如果重新生成代码,则将覆盖对此文件的手动更改。
// </auto-generated>
//------------------------------------------------------------------------------
namespace MvcApplication1.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Goods
{
public int GoodsID { get; set; }
[Required(ErrorMessage = "商品名称是必填项")]//必填
[StringLength(10, ErrorMessage = "长度错误")]//长度限制
public string GoodsName { get; set; }
[Required(ErrorMessage = "商品价格是必填项")]//必填
public decimal GoodsPrice { get; set; }
[Required(ErrorMessage = "商品库存是必填项")]//必填
public int GoodsStock { get; set; }
}
}
DAL
cs
public static bool AddGood(Goods good)
{
GoodsDBEntities db = new GoodsDBEntities();
db.Goods.Add(good);
return db.SaveChanges() > 0;
}
BLL
cspublic static bool AddGood(Goods good) { return DAL.GoodsService.AddGood(good); }
Index
cs
@Html.ActionLink("添加", "AddGood")
ADD
html
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>AddGood</title>
</head>
<body>
<div>
<form action="/Home/AddGood" method="post">
商品名称<input type="text" name="GoodsName" value="@(ViewBag.Good!=null? ViewBag.Good.GoodsName:"")" /> @Html.ValidationMessage("GoodsName")<br />
商品价格<input type="text" name="GoodsPrice" /> @Html.ValidationMessage("GoodsPrice")<br />
商品库存<input type="text" name="GoodsStock" />@Html.ValidationMessage("GoodsStock")<br />
<input type="submit" value="保存" />
@Html.ValidationSummary()
</form>
</div>
</body>
</html>