VUE的增删改查

 

一、添加

1.DAL层

//例子:
/// <summary>
/// 添加
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public int Add(StudentInfo info)
{
db.StudentInfos.Add(info);
return db.SaveChanges();
}

2.控制器

注意:方法和视图必须分开

 //视图:
public ActionResult AddStudent()
      {
          return View();
      }
 //方法:
[HttpPost]
      public ActionResult Add(StudentInfo info)
      {
          return Json(bll.Add(info), JsonRequestBehavior.DenyGet);
      }

3.视图

注意:vue.js和axios.js顺序必定不能返

<script src="~/Scripts/vue.js"></script>
<script src="~/Scripts/axios.js"></script>
<h2>AddStudent</h2>
<div id="app">
  <table class="table table-bordered">
      <tr>
          <td>学生姓名</td>
          <td><input type="text" v-model="formData.SName" value="" /></td>
      </tr>
      <tr>
          <td>学生班级</td>
          <td>
              <select v-model="formData.NId">
                  <option v-for="(item,index) in selectItems" :value="item.NId">{{item.NName}}</option>
              </select>
          </td>
      </tr>
      <tr>
          <td>学生年龄</td>
          <td><input type="text" v-model="formData.Age" value="" /></td>
      </tr>
      <tr>
          <td>学生性别</td>
          <td>
              <input type="radio" name="sex" v-model="formData.Sex" value="true" />男
              <input type="radio" name="sex" v-model="formData.Sex" value="false" />女
          </td>
      </tr>
      <tr>
          <td>学生爱好</td>
          <td>
              <input type="checkbox" name="hobby" v-model="items" value="游泳" />游泳
              <input type="checkbox" name="hobby" v-model="items" value="跳水" />跳水
              <input type="checkbox" name="hobby" v-model="items" value="冲浪" />冲浪
          </td>
      </tr>
      <tr>

          <td colspan="2"><input type="button" class="btn btn-success" value="添加" v-on:click="addstudent" /></td>
      </tr>

  </table>
</div>
<script>
  let app = new Vue({
      el: "#app",
      created: function () {
          this.getSelect();
      },
      data() {
          return {
              formData: {
                  NId: '1',
                  SName: '',
                  Sex: 'true',
                  Hobby: [],
                  Age: ''
              },
              selectItems: [],
              items:[]
          }
      },
      methods: {
          //加载下拉菜单
          getSelect() {
              axios.get('/Student/BinClass').then(res => {
                  this.selectItems=res.data
              })
          },
          //添加数据
          addstudent() {
              this.formData.Hobby = this.items.join(',');
              axios.post('/Student/Add', this.formData).then(res => {
                  if (res.data > 0) {
                      alert("添加成功");
                  }
                  else {
                      alert("添加失败");
                  }
              })
          }
      }
  })
</script>

二、分页显示、查询

1.DAL层

 //定义实体类来接收数据、总条数、总页数
public class PageData<T> where T:class //给当前泛型添加约束
  {
      public int Totalcount { get; set; }
      public int Totalpage { get; set; }
      public List<T> Data { get; set; }
  }

 

 /// <summary>
      /// 分页显示
      /// </summary>
      /// <param name="totalcount"></param>
      /// <param name="totalpage"></param>
      /// <param name="sname"></param>
      /// <param name="nid"></param>
      /// <param name="pageindex"></param>
      /// <param name="pagesize"></param>
      /// <returns></returns>
      public PageData<ViewModel> PageShow(string sname,int nid,int pageindex,int pagesize)
      {
      //实例化泛型类用来接收数据
          PageData<ViewModel> pd = new PageData<ViewModel>();
          var list = from a in db.StudentInfos
                      join b in db.NClasss on a.NId equals b.NId
                      select new ViewModel
                      {
                          SId = a.SId,
                          SName = a.SName,
                          Age = a.Age,
                          Sex = a.Sex,
                          Hobby = a.Hobby,
                          NId = a.NId,
                          NName = b.NName
                      };
          if (!string.IsNullOrEmpty(sname))
          {
              list = list.Where(p => p.SName.Contains(sname));
          }
          if (nid > 0)
          {
              list = list.Where(p => p.NId == nid);
          }
          //总条数
          pd.Totalcount = list.Count();
          //总页数
          pd.Totalpage = Convert.ToInt32(Math.Ceiling(pd.Totalcount * 1.0 / pagesize));
          //数据
          pd.Data= list.OrderBy(p => p.SId).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
          return pd;
      }

2.控制器

注意:方法和视图必须分开

public ActionResult Index()
      {
          return View();  
      }
 [HttpGet]
      public ActionResult PageShow(string sname, int nid=0, int pageindex=1, int pagesize=2)
      {
          var list = bll.PageShow(sname, nid, pageindex, pagesize);
          return Json(list, JsonRequestBehavior.AllowGet);
      }

3.视图

<script src="~/Scripts/vue.js"></script>
<script src="~/Scripts/axios.js"></script>
<h2>当前用户:@((Session["UserInfo"]as Model.UserInfo).UserName)</h2>
<div id="app">
  <div>
      学生姓名: <input type="text" name="name" value="" v-model="sname" />
      学生班级:
      <select v-model="nid">
          <option v-for="(item1,index1) in selectItems" :value="item1.NId">{{item1.NName}}</option>
      </select>
      <input type="button" class="brn btn-primary" value="查询" v-on:click="loadData" />
      <input type="button" class="btn btn-danger" value="批量删除" v-on:click="delAll" />
      <input type="button" class="btn btn-warning" value="批量修改" v-on:click="bachEidt" />
  </div>
  <table class="table table-bordered">
      <tr>
          <td><input type="checkbox" name="name" value=""v-model="chk" v-on:click="setChecked" /></td>
          <td>姓名</td>
          <td>性别</td>
          <td>年龄</td>
          <td>爱好</td>
          <td>班级</td>
      </tr>
      <tr v-for="(item,index) in list">
          <td><input type="checkbox" name="name" :value="item.SId" v-model="chks" /></td>
          <td>{{item.SName}}</td>
          <td>{{item.Sex?"男":"女"}}</td>
          <td>{{item.Age}}</td>
          <td>{{item.Hobby}}</td>
          <td>{{item.NName}}</td>
          <td><a href="#" v-on:click="eidt(item.SId)">编辑</a> <a href="#">删除</a></td>
      </tr>
  </table>
  <div>
      <a href="#" v-on:click="page('F')">首页</a>
      <a href="#" v-on:click="page('P')">上一页</a>
      <a href="#" v-on:click="page('N')">下一页</a>
      <a href="#" v-on:click="page('L')">尾页</a>
      <span>当前{{pageindex}}/{{totalpage}}页 共{{totalcount}}条</span>
      跳转 <input type="text" name="name" style="width:40px" />
      <input type="button" class="btn btn-warning" value="Go" />
  </div>
</div>
<script>
  let app = new Vue({
      el: "#app",
      data() {
          return {
              list: [],
              totalcount: 0,
              totalpage: 0,
              selectItems: [],
              sname: "",
              nid: 0,
              pageindex:1,
              pagesize: 2,
              chk: false,//主复选框
              chks:[] //副 复选框
          }
      },
      methods: {
          loadData() {
              axios.get('http://localhost:64827/Student/PageShow/?sname=' + this.sname + '&nid=' + this.nid + '&pageindex=' + this.pageindex + '&pagesize=' + this.pagesize + '').then(res => {
                  this.list = res.data.Data;
                  this.totalcount = res.data.Totalcount;
                  this.totalpage = res.data.Totalpage;
              })
          },
          loadSelect() {
              axios.get('/Student/BinClass').then(res => {
                  this.selectItems = res.data;
                  this.selectItems.unshift({ "NId": "0", "NName": "请选择" });
              })
          },
          page(o) {
              switch (o) {
                  case 'F': this.pageindex = 1; break;
                  case 'P': this.pageindex = this.pageindex <= 1 ? this.pageindex : this.pageindex - 1; break;
                  case 'N': this.pageindex = this.pageindex >= this.totalpage ? this.totalpage : this.pageindex + 1; break;
                  case 'L': this.pageindex = this.totalpage; break;
                   
              }
              this.loadData();
          },
          //全选
          setChecked() {
              if (!this.chk) {
                  for (var i = 0; i < this.list.length; i++) {
                      this.chks.push(this.list[i].SId)
                  }
              }
              else {
                  this.chks = [];
              }
          }
      },
      created: function () {
          this.loadData();
          this.loadSelect();
      }
  })
</script>

三、批量删除和批量修改状态

1.DAL层

 /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int DelAll(string ids)
        {
            var id = ids.Split(',');
            foreach (var item in id)
            {
                var idd = Convert.ToInt32(item);
                var list = db.StudentInfos.FirstOrDefault(p => p.SId == idd);
                db.StudentInfos.Remove(list);
            }
            return db.SaveChanges();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="sex"></param>
        /// <returns></returns>
        public int BachEidt(string ids,bool sex)
        {
            var id = ids.Split(',');
            foreach (var item in id)
            {
                var idd = Convert.ToInt32(item);
                var list = db.StudentInfos.FirstOrDefault(p => p.SId == idd);
                list.Sex = sex;
            }
            return db.SaveChanges();
        }

2.控制器

    [HttpGet]
    public ActionResult DelAll(string ids)
    {
    return Json(bll.DelAll(ids),JsonRequestBehavior.AllowGet);
    }
    [HttpGet]
    public ActionResult BachEidt(string ids, bool sex)
    {
    return Json(bll.BachEidt(ids, sex),JsonRequestBehavior.AllowGet);
    }

3.视图

			//批量删除
			delAll() {
                if (this.chks.length == 0) {
                    alert("请选择要删除的数据")
                    return;
                }
                if (confirm("确定要删除吗?")) {
                    axios.get('/Student/DelAll?ids=' + 											this.chks.toString()).then(res => {
                        if (res.data > 0) {
                            alert("删除成功!");
                            this.loadData();
                        }
                    })
                }
                
            },
            //批量修改
            bachEidt() {
                if (this.chks.length == 0) {
                    alert("请选择要修改的数据")
                    return;
                }
                if (confirm("确定要修改吗?")) {
                    axios.get('/Student/BachEidt', {
                        params: {
                            ids: this.chks.toString(),
                            sex: false
                        }
                    }).then(res => {
                        if (res.data > 0) {
                            alert("修改成功!");
                            this.loadData();
                        }
                    })
                }
             
            }

四、编辑

1.DAL层

		/// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public StudentInfo Eidt(int id)
        {
            return db.StudentInfos.FirstOrDefault(p => p.SId == id);
        }

2.控制器

注意:方法和视图必须分开

public ActionResult EidtStudent()
        {
            return View();
        }
[HttpGet]
        public ActionResult Eidt(int id)
        {
            return Json(bll.Eidt(id), JsonRequestBehavior.AllowGet);
        }

3.视图

<script src="~/Scripts/vue.js"></script>
<script src="~/Scripts/axios.js"></script>
<h2>AddStudent</h2>
<div id="app">
    <table class="table table-bordered">
        <tr>
            <td>学生姓名</td>
            <td><input type="text" v-model="formData.SName" value="" /></td>
        </tr>
        <tr>
            <td>学生班级</td>
            <td>
                <select v-model="formData.NId">
                    <option v-for="(item,index) in selectItems" :value="item.NId">{{item.NName}}</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>学生年龄</td>
            <td><input type="text" v-model="formData.Age" value="" /></td>
        </tr>
        <tr>
            <td>学生性别</td>
            <td>
                <input type="radio" name="sex" v-model="formData.Sex" value="true" />男
                <input type="radio" name="sex" v-model="formData.Sex" value="false" />女
            </td>
        </tr>
        <tr>
            <td>学生爱好</td>
            <td>
                <input type="checkbox" name="hobby" v-model="items" value="游泳" />游泳
                <input type="checkbox" name="hobby" v-model="items" value="跳水" />跳水
                <input type="checkbox" name="hobby" v-model="items" value="冲浪" />冲浪
            </td>
        </tr>
        <tr>

            <td colspan="2"><input type="button" class="btn btn-success" value="修改" v-on:click="addstudent" /></td>
        </tr>

    </table>
</div>
<script>
    var id = location.search.substring(4);
    let app = new Vue({
        el: "#app",
        created: function () {
            this.getSelect();
            this.getById();
        },
        data() {
            return {
                formData: {
                    SId:0,
                    NId: '1',
                    SName: '',
                    Sex: 'true',
                    Hobby: [],
                    Age: ''
                },
                selectItems: [],
                items: []
            }
        },
        methods: {
            //加载下拉菜单
            getSelect() {
                axios.get('/Student/BinClass').then(res => {
                    this.selectItems = res.data
                })
            },
         	//编辑
            getById() {
                axios.get('/Student/Eidt?id=' + id).then(res => {
                    this.formData.NId = res.data.NId;
                    this.formData.SName = res.data.SName;
                    this.formData.Sex = res.data.Sex;
                    this.formData.Age = res.data.Age;
                    this.formData.Hobby = res.data.Hobby;
                    this.formData.SId = res.data.SId;
                    this.items = res.data.Hobby.split(',');
                })
            }
        }
    })
</script>

五、修改

1.DAL层

		/// <summary>
        /// 修改
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public int Update(StudentInfo info)
        {
            db.Entry(info).State = System.Data.Entity.EntityState.Modified;
            return db.SaveChanges();
        }

2.控制器

		[HttpPost]
        public ActionResult Update(StudentInfo info)
        {
            return Json(bll.Update(info),JsonRequestBehavior.DenyGet);
        }

3.视图

			//修改数据
            addstudent() {
                this.formData.Hobby = this.items.join(',');
                axios.post('/Student/Update', this.formData).then(res => {
                    if (res.data > 0) {
                        alert("修改成功");
                        location.href = '/Student/Index';
                    }
                    else {
                        alert("修改失败");
                    }
                })
            }

 

上一篇:【开源】QuickPager ASP.NET2.0分页控件V2.0.0.7 增加了一个js函数的分页方式。


下一篇:html+vue.js 实现分页可兼容IE