欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.NET架构MVC5编程实现简易购物网站

程序员文章站 2022-05-16 20:33:52
1.首先先创建一个数据模型类product; namespace mvcgw.models { public class product { publ...

1.首先先创建一个数据模型类product;

.NET架构MVC5编程实现简易购物网站
namespace mvcgw.models
{
    public class product
    {
        public int id { get; set; }
        [display(name = "商品名称")]
        [required(errormessage = "必填")]
        [stringlength(60, minimumlength = 3, errormessage = "必须是[3,60]个字符")]
        public string title { get; set; }
        [display(name = "商品类型")]
        [required]
        public string genre { get; set; }
        [display(name = "商品简介")]
        [required]
        public string description { get; set; }
        [display(name = "商品售价")]
        [range(1, 10000)]
        [datatype(datatype.currency)]
        public decimal price { get; set; }
        [display(name = "上新日期")]
        [datatype(datatype.date)]
        public datetime releasedate { get; set; }
        [display(name = "商品图片")]
        [required]
        public string photo { get; set; }
    }

还有shoppingcar(购物车)类和order(订单)类,

为了在中保存图片,保存的是图片路径;

2.创建数据库上下文类;

public class productdbcontext : dbcontext
    {
        public dbset<product> products { get; set; }
        public dbset<shoppingcar> shoppingcars { get; set; }
        public dbset<order> orders { get; set; }
    }

3.创建数据库连接串;

//web.config文件: 
<connectionstrings>
    <add name="productdbcontext"
             connectionstring="data source=(localdb)\v11.0;
                                           attachdbfilename=|datadirectory|\products.mdf;
                                            attachdbfilename=|datadirectory|\shoppingcars.mdf;
                                             attachdbfilename=|datadirectory|\orders.mdf;
                                           integrated security=true"
             providername="system.data.sqlclient" />
  </connectionstrings>

4。添加视图

笔者的网站使用了layout布局,这样代码利用率高

@model ienumerable<mvcgw.models.product>
@{
    viewbag.title = "index";
    layout = "~/views/shared/_layout.cshtml";
}
<style>
    .big {
        margin: 0px auto 0px auto;
        width: 940px;
        height: 516px;
       /* background-image: url('/images/tjsp_border.jpg'); /*推荐商品背景图片*/
        padding: 45px 20px 21px 20px; /*背景图片框有一定的厚度*/
    }


    .flower {
        width: 225px;
        height: 235px;
        float: left; /*图片并排*/
        padding: 12px;
        /*border:1px #cccccc solid;text-align:center;*/
        overflow: hidden;
    }


    .flower_desc {
        height: 25px;
        line-height: 30px;
        text-align: center;
        font-size: 12px;
    }
</style>
<p>
    @using (html.beginform("index", "product", formmethod.get))
    {
        <p>
            宝贝类型:@html.dropdownlist("bbgenre", "all")
            <input type="submit" value="查询" />
        </p>
    }


</p>
<p class="big">
    @foreach (var m in model)
    {
        <p class="flower">
            <p><img src="/@m.photo"width="170" height="160" /></p>
            <p class="flower_desc">@m.title.trim() &nbsp;&nbsp;@m.price 元 </p><br />
            @html.actionlink("加入购物车", "putcar", new { id = m.id }) |
            @html.actionlink("详情", "details", new { id = m.id }) 
             
        </p>
    }
</p>

可使用应用list模板

5.创建控制器productcontroller,实现实现业务逻辑

编写index,

public actionresult index(string bbgenre)
        {
            var genrelst = new list<string>();//实现按宝贝类型查询,控制器传递数据给select的方法
            var genreqry = from d in db.products orderby d.genre select d.genre;
            genrelst.addrange(genreqry.distinct());    //去重
            viewbag.bbgenre = new selectlist(genrelst);//设置的viewbag属性值一定要与select的name保持一致
            var rs1 = from m in db.products
                     select m;
            if (!string.isnullorempty(bbgenre))
            { rs1 = rs1.where(x => x.genre == bbgenre); return view(rs1); }
            var rs = from m in db.products
                     where new int[] { 1,2,3,4,5,6,7,8 }.contains(m.id)
                     select m;
   return view(rs); //向视图传递的数据是对象rs
                             /*viewdata.model = rs;
                             return view();*/
        }
 public actionresult putcar(int id)
        {
            //会员登录后才能购物
            if (session["username"] == null)
                return redirecttoaction("login", "product");
 
            var rec1 = db.products.find(id);
            //默认数量sl=1,在生成订单前可以修改                 
            shoppingcar rec2 = new shoppingcar { username = (string)session["username"],  title = rec1.title, price = rec1.price,genre=rec1.genre, photo = rec1.photo, num = 1 };
            db.shoppingcars.add(rec2);
            db.savechanges();
           return redirecttoaction("index");
        }
        public actionresult shoppingcar()
        { decimal i = 0;
            var sc = from m in db.shoppingcars select m;


            if (session["username"] != null)
            {
                string name = (string)session["username"];
                sc = sc.where(s => s.username.contains(name));


                foreach (var item in sc)
                {
                    i += item.price;
                }
                viewbag.data = i;//后台算出总价传值给前台视图
                return view(sc);
            }
            else return redirecttoaction("login", "product");
        }
     public actionresult besure()//实现确认购买生成订单,向订单类中添加已购买商品数据,购物车清空
        {
            var sc = from m in db.shoppingcars select m;


            if (session["username"] != null)
            {
                string name = (string)session["username"];
                sc = sc.where(s => s.username==name) ;


                foreach (var rec1 in sc)
                {
                                     
                    order rec2 = new order { username = (string)session["username"], title = rec1.title, price = rec1.price, genre = rec1.genre, photo = rec1.photo, num = 1 };
                    db.orders.add(rec2);
                     
                }
                foreach (var rec3 in sc)
                {
                    
                    db.shoppingcars.remove(rec3);
              
                }
                db.savechanges();
                return redirecttoaction("order");
            }
            else return redirecttoaction("login", "product");


  }
        public actionresult order()
        {
            decimal i = 0;
            var sc = from m in db.orders select m;


            if (session["username"] != null)
            {
                string name = (string)session["username"];
                sc = sc.where(s => s.username.contains(name));


                foreach (var item in sc)
                {
                    i += item.price;
                }
                viewbag.data1 = i;
                return view(sc);
            }
            else return redirecttoaction("login", "product");
}
.NET架构MVC5编程实现简易购物网站