1. 程式人生 > 實用技巧 >君仙小一時的第二週溫習

君仙小一時的第二週溫習

我是先寫的Model的表:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MODEL
{
    [Table("MyFavorite")]
    public class MyFavorite
    {
        [Key]
        public string UserId { get; set; }
        public string Pno { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MODEL
{
    [Table("MyShoppingCar")]
    public class MyShoppingCar
    {
        [Key]
        public int  Id { get; set; }
        public string UserId { get; set; }
        public string Pno { get; set; }
        public int? Account { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MODEL
{
    [Table("Product")]
    public class Product
    {
        [Key]
        public int Id { get; set; }
        public string Pno { get; set; }
        public string Pname { get; set; }
        public int? Price { get; set; }
        public string ImgPath { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MODEL
{
    [Table("UserInfo")]
    public class UserInfo
    {
        [Key]
        public String UserID { get; set; }
        public String UserName { get; set; }
        public String WX { get; set; }
        public String Pwd { get; set; }
        public String QQ { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MODEL
{
   public  class V_MyShoppingCar
    {
        public int Id { get; set; }
        public string Pno { get; set; }
        public int? Account { get; set; }
        public string Pname { get; set; }
        public string ImgPath { get; set; }        
        public int? Price { get; set; }
        public int? TotalMoney { get; set; }
    }
}

 

然後再寫資料訪問層:

namespace DAL
{
    using System;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using MODEL;


    public partial class Model1 : DbContext
    {
        public Model1()
            : base("name=Model1")
        {
        }

        public virtual DbSet<Product> Products { get; set; }
        public virtual DbSet<UserInfo> UserInfos { get; set; }
        public virtual DbSet<MyShoppingCar> MyShoppingCars { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>()
                .Property(e => e.Pno)
                .IsUnicode(false);

            modelBuilder.Entity<Product>()
                .Property(e => e.Pname)
                .IsUnicode(false);

            modelBuilder.Entity<Product>()
                .Property(e => e.ImgPath)
                .IsUnicode(false);

            modelBuilder.Entity<UserInfo>()
                .Property(e => e.UserID)
                .IsUnicode(false);

            modelBuilder.Entity<UserInfo>()
                .Property(e => e.UserName)
                .IsUnicode(false);

            modelBuilder.Entity<UserInfo>()
                .Property(e => e.WX)
                .IsUnicode(false);

            modelBuilder.Entity<UserInfo>()
                .Property(e => e.QQ)
                .IsUnicode(false);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class MyFavoriteDAL
    {
        public int Favorite(string userid,string pnos)
        {
            string[] arr = pnos.Trim(',').Split(',');
            using (Model1 mc = new Model1())
            {
                foreach (string str in arr)
                {
                    string sql = $"insert into MyFavorite(userid,pno) values('{userid}','{str}')";
                    mc.Database.ExecuteSqlCommand(sql);
                }
            }
                
            return 1;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MODEL;

namespace DAL
{
    public class MyShoppingCarDAL
    {
        public int AddMyShoppingCar(string userid, string pnos)
        {
            string[] arr = pnos.Trim(',').Split(',');
            using (Model1 mc = new Model1())
            {
                foreach (string str in arr)
                {
                    string sql = $"insert into MyShoppingCar(userid,pno,Account) values('{userid}','{str}',1)";
                    mc.Database.ExecuteSqlCommand(sql);
                }
            }

            return 1;
        }

        //獲取購物車的資訊
        public List<V_MyShoppingCar> GetList(string userid)
        {
            using (Model1 mc = new Model1())
            {

                var query = from s in mc.Products
                            from t in mc.MyShoppingCars
                            where s.Pno == t.Pno && t.UserId== userid
                            select new V_MyShoppingCar { Pno = s.Pno, Pname = s.Pname, Price = s.Price, Id = t.Id, Account = t.Account, TotalMoney = t.Account * s.Price, ImgPath=s.ImgPath };
                return query.ToList();
            }
        }

        //批量刪除
        public int DelMyShoppingCars(string ids)
        {
            //1,2,3,4,....
            using (Model1 mc = new Model1())
            {
                string sql = $"delete MyShoppingCar where id in({ids.Trim(',')})";
                mc.Database.ExecuteSqlCommand(sql);
            }
            return 1;
        }

        //加減1
        public int MyShoppingCarsUpDown(string id,string sType)
        {
            using (Model1 mc = new Model1())
            {
                string sql;
                if (sType.Equals("up"))
                     sql = $"update MyShoppingCar set Account=Account+1 where id={id}";
                else
                    sql = $"update MyShoppingCar set Account=Account-1 where id={id}";
                mc.Database.ExecuteSqlCommand(sql);
            }
            return 1;
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MODEL;

namespace DAL
{
    public class ProductDAL
    {
        public List<Product> GetList(string pname)
        {
            using (Model1 mc = new Model1())
            {
                return mc.Products.Where(x=>x.Pname.Contains(pname)).ToList();
            }
        }



    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class UserInfoDAL
    {
        public int Login(string userid,string pwd)
        {
            using (Model1 mc = new Model1())
            {
               return mc.UserInfos.Where(x => x.UserID.Equals(userid) && x.Pwd.Equals(pwd)).Count();
            }
        }
    }
}

  

然後就是賊簡單的邏輯:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;

namespace BLL
{
    public class MyFavoriteBLL
    {
        MyFavoriteDAL dal = new MyFavoriteDAL();
        public int Favorite(string userid, string pnos)
        {
            return dal.Favorite(userid, pnos);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MODEL;
using DAL;

namespace BLL
{
    public class MyShoppingCarBLL
    {
        MyShoppingCarDAL dal = new MyShoppingCarDAL();
        public int AddMyShoppingCar(string userid, string pnos)
        {
            return dal.AddMyShoppingCar(userid, pnos);
        }

        //獲取購物車的資訊
        public List<V_MyShoppingCar> GetList(string userid)
        {
            return dal.GetList(userid);
        }

        //批量刪除
        public int DelMyShoppingCars(string ids)
        {
            return dal.DelMyShoppingCars(ids);
        }

        //加減1
        public int MyShoppingCarsUpDown(string id, string sType)
        {
            return dal.MyShoppingCarsUpDown(id, sType);
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using MODEL;

namespace BLL
{
    public class ProductBLL
    {
        ProductDAL dal = new ProductDAL();
        public List<Product> GetList(string pname)
        {
            return dal.GetList(pname);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;

namespace BLL
{
    public class UserInfoBLL
    {
        UserInfoDAL dal = new UserInfoDAL();
        public int Login(string userid, string pwd)
        {
            return dal.Login(userid, pwd);
        }
    }
}

  

接下來就是我研究了好長時間的控制器 :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using MODEL;

namespace WT01.Controllers
{
    public class HomeController : Controller
    {
        UserInfoBLL bll = new UserInfoBLL();

        //登入
        public ActionResult Login()
        {
            return View();
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult MyShoppingCar()
        {
            return View();
        }

        //登入驗證
        [HttpPost]
        public int LoginValidate(string userid,string pwd)
        {
            HttpContext.Session["userid"] = userid;
            return bll.Login(userid, pwd);
        }

        //收藏
        [HttpPost]
        public int Favorite(string pnos)
        {
            string userid= HttpContext.Session["userid"].ToString();
            return  new MyFavoriteBLL().Favorite(userid, pnos);
        }

        //加入購物車
        [HttpPost]
        public int AddMyShoppingCar(string pnos)
        {
            string userid = HttpContext.Session["userid"].ToString();
            return new MyShoppingCarBLL().AddMyShoppingCar(userid, pnos);
        }


        //獲取產品的List
        [HttpGet]
        public JsonResult GetList(string pname)
        {
            ProductBLL productBLL = new ProductBLL();
            return Json(productBLL.GetList(pname),JsonRequestBehavior.AllowGet);
        }


        //獲取我的購物車列表資訊List
        [HttpGet]
        public JsonResult GetMyShoppingCarList()
        {
            MyShoppingCarBLL myShoppingCar = new MyShoppingCarBLL();
            string userid = HttpContext.Session["userid"].ToString();          
            return Json(myShoppingCar.GetList(userid), JsonRequestBehavior.AllowGet);
        }

        //批量刪除購物車
        [HttpPost]
        public int DelMyShoppingCar(string ids)
        {
            return new MyShoppingCarBLL().DelMyShoppingCars(ids);
        }

        //加減1
        [HttpPost]
        public int MyShoppingCarsUpDown(string id, string sType)
        {
            return new MyShoppingCarBLL().MyShoppingCarsUpDown(id, sType);
        }

    }
}

  

最後就是我不是特別喜歡寫的頁面了,比較報錯都是在寫完頁面之後滴(T_T)/~~

index頁面:

@{
    ViewBag.Title = "Home Page";
    Layout = null;
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>

<script>

    //文件就緒函式
    $(function () {
        QueryList();
    })

    //收藏
    function MyFavorite() {
        var arr = document.getElementsByName("xselect");
        var str = "";
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].checked)
                str += arr[i].id + ",";
        }
        //alert(str);
        $.ajax({
            url: '/Home/Favorite',
            type: 'post',
            dataType: 'json',
            data: { pnos: str },
            success: function (data) {
                if (data > 0)
                    alert("收藏成功!");
            }
        })
    }

    //加入購物車
    function MyShoppingCar() {
        var arr = document.getElementsByName("xselect");
        var str = "";
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].checked)
                str += arr[i].id + ",";
        }
        //alert(str);
        $.ajax({
            url: '/Home/AddMyShoppingCar',
            type: 'post',
            dataType: 'json',
            data: { pnos: str },
            success: function (data) {
                if (data > 0)
                    alert("加入購物車成功!");
            }
        })
    }

    //轉到我的購物車
    function ToMyShoppingCar() {
        location.href ='/Home/MyShoppingCar'
    }
    //查詢資訊
    function QueryList() {
        var content = $("#txtContent").val();

        $.ajax({
            url: '/Home/GetList',
            type: 'get',
            dataType: 'json',
            data: { pname: content },
            success: function (data) {
                $("#tbProduct").empty();
                for (var i = 0; i < data.length; i++) {
                    var tr = ' <tr>';
                    tr += ' <td>';
                    tr += '<img src="../' + data[i].ImgPath + '" />';
                    tr += '<br>';
                    tr += data[i].Price;
                    tr += '<br>';
                    tr += data[i].Pname;
                    tr += '<br>';
                    tr += '<input name="xselect" type="checkbox" id="' + data[i].Pno + '" />';
                    tr += ' </td>';

                    tr += "</tr>";
                    $("#tbProduct").append(tr);
                }
            }
        })
    }

</script>

<input type="text" id="txtContent" /><input value="查詢" type="button" onclick="QueryList();" /><input value="收藏" type="button" onclick="MyFavorite();" /><input value="加入購物車" type="button" onclick="MyShoppingCar();" /><input value="我的購物車" type="button" onclick="ToMyShoppingCar();" />
<table id="tbProduct"></table>

  

login頁面:

@{
    ViewBag.Title = "Login";
   
}
<h2>Login</h2>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>

    //驗證登入
    function LoginCheck() {
        var userid = $("#txtAmount").val();
        var pwd = $("#txtPwd").val();

        if (userid == "") {
            alert("賬號不能為空!");
            return;
        }
        if (pwd == "") {
            alert("賬號不能為空!");
            return;
        }


        $.ajax({
            url: '/Home/LoginValidate',
            type: 'post',
            dataType: 'json',
            data: { userid: userid, pwd: pwd },
            success: function (data) {
                if (data > 0) {
                    location.href = '/Home/Index';
                }
                else {
                    alert("賬號或密碼錯誤,請重新輸入");
                    location.href = '/Home/Login';
                }
            }
        })
    }

</script>
<table border="1">
    <tr>
        <td>賬號:</td>
        <td><input type="text" id="txtAmount" /></td>
    </tr>
    <tr>
        <td>密碼:</td>
        <td><input type="password" id="txtPwd" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input value="登入" type="button" id="btnLogin" onclick="LoginCheck()"  />
        </td>
    </tr>
</table>

  

我的顯示頁面:

@{
    ViewBag.Title = "MyShoppingCar";
   // Layout = null;
}

<h2>我的購物車</h2>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>

    //文件就緒函式
    $(function () {
        QueryList();
    })   

    //全選
    function CheckAll(o) {
        var chks = document.getElementsByName("xselect");
        for (var i = 0; i < chks.length; i++) {
            chks[i].checked = o.checked;
        }
    }

    //批量刪除
    function BathDel() {
        var chks = document.getElementsByName("xselect");
        var ids = "";
        for (var i = 0; i < chks.length; i++) {
            if (chks[i].checked)
                ids+=  chks[i].id+",";
        }
        $.ajax({
            url: '/Home/DelMyShoppingCar',
            type: 'post',
            dataType: 'json',
            data: { ids: ids },
            success: function (data) {
                if (data > 0) {
                    QueryList();
                    alert('刪除成功!');
                }
            }
        })
    }

    //刪除
    function DelBid(id) {      
        $.ajax({
            url: '/Home/DelMyShoppingCar',
            type: 'post',
            dataType: 'json',
            data: { ids: id },
            success: function (data) {
                if (data > 0) {
                    QueryList();
                    alert('刪除成功!');
                }
            }
        })

    }

    //加減1
    function upDown(id, sType) {
        $.ajax({
            url: '/Home/MyShoppingCarsUpDown',
            type: 'post',
            dataType: 'json',
            data: { id: id, sType: sType},
            success: function (data) {
                if (data > 0) {
                    QueryList();                  
                }
            }
        })

    }

    //查詢資訊
    function QueryList() {

        $.ajax({
            url: '/Home/GetMyShoppingCarList',
            type: 'get',
            dataType: 'json',        
            success: function (data) {
                $("#tbProduct").empty();
                for (var i = 0; i < data.length; i++) {
                    var tr = ' <tr>';

                    //商品
                    tr += ' <td>';
                    tr += '<input name="xselect" type="checkbox" id="' + data[i].Id + '" />';
                    tr += '<img src="../' + data[i].ImgPath + '" />';
                    tr += '<br>';
                    tr += data[i].Pname;
                    tr += ' </td>';

                    //單價
                    tr += ' <td>';
                    tr += data[i].Price;
                    tr += ' </td>';

                    //數量
                    tr += ' <td>';
                    tr += '<a href="javascript:upDown(' + data[i].Id + ',\'down\')">-</a><input type="text" value="' + data[i].Account + '"  style="width:20px" /><a href="javascript:upDown(' + data[i].Id + ',\'up\')">+</a>';
                    tr += ' </td>';

                    //小計
                    tr += ' <td>';
                    tr += data[i].TotalMoney;
                    tr += ' </td>';

                    //操作
                    tr += ' <td>';
                    tr += '<input type="button" value="刪除" onclick="DelBid(' + data[i].Id+')" />';
                    tr += ' </td>';

                    tr += "</tr>";
                    $("#tbProduct").append(tr);
                }
            }
        })
    }

</script>
<table border="1" width="100%">
    <thead>
        <tr>
            <th>
                <input type="checkbox" onclick="CheckAll(this)" />全選商品
            </th>
            <th>
                單價
            </th>
            <th>
                數量
            </th>
            <th>
                小計
            </th>
            <th>
                操作
            </th>
        </tr>
    </thead>
    <tbody id="tbProduct">

    </tbody>
</table>
<input type="button" value="批量刪除" onclick="BathDel()"/>

  

希望以上程式碼對大家有幫助( ^∀^)

記得推薦加關注(☆_☆)/~~