MVC 更新部分字段 (数据库先行)

<参考资料:EF对数据的增删查改>

    public class HomeController : Controller
    {

        salesEntities db = new salesEntities();

        public ActionResult Index()
        {
       

            var q = db.User.Single(x => x.id == 1); //获取 id等于1的一条数据(实体)
            var data = q.UserName = "王五"; //将这条数据的UserName修改为“王五”

            UpdateModel<User>(q); //更新此条数据;注意q是一从db中查询出来的。(如果不是从db中查询得到,则UpdateModel这句代码无效)

           
            //db.User.Add(q); //再将此条数据添加到数据库表中 

            //db.User.Remove(q);//然后再删除此条数据
            
            
            db.SaveChanges(); //将之前的所有操作更新到数据库
            return View();
            
        }

    }




====================================MVC 更新部分字段  数据库先行===========================================


<1>首先是在项目中添加一个ADO.NET实体数据模型,选择MemberInfo表 他会自动在模型里面生成一个MemberInfo的类,也会生成一个对应的实体类DataBaseEntities。用的时候只有用模型里的MemberInfo类和DataBaseEntities就好了。 不需再额外添加MemberInfo类了  【注意:这个DataBaseEntities 是你的数据库名字+Entities】

<1>

MemeberCenter控制器

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

namespace bigtree.Controllers
{

    public class MemberCenterController : Controller
    {

        bigTreeEntities db = new bigTreeEntities();
        public ActionResult Index(int id)
        {
            ViewData["uid"] = id;
            
            return View();
        }


        /// <summary>
        /// 从实体中查询出一条数据出来,然后将这条数据保存到ViewData.Model中 。这样在Info视图里就可以根据Model来取数据了
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Info(int id)
        {
            ViewData["uid"] = id;

            //var queryUserInfo = from d in db.MemberInfo
            //                    where d.id == id
            //                    select d;

            //ViewData.Model = queryUserInfo.Single();

            var queryUserInfo = db.MemberInfo.Single(x => x.id == id);

            var data= MemberDetail.ConvertToViewModel(queryUserInfo);
            ViewData.Model = data;
           

            return View();
        }

        //[HttpPost]
        //public ActionResult Info(bigtree.MemberInfo newsMemberInfo)
        //{
        //    //db.MemberInfo.Attach(newsMemberInfo);
        //    //db.ObjectStateManager.ChangeObjectState(newsMemberInfo, System.Data.EntityState.Modified);
        //    //db.SaveChanges();

        //    bigtree.MemberInfo oldMemberInfo = db.MemberInfo.FirstOrDefault(x => x.id == newsMemberInfo.id);
        //    oldMemberInfo.mobile = newsMemberInfo.mobile;
        //    oldMemberInfo.name = newsMemberInfo.name;
        //    oldMemberInfo.email = newsMemberInfo.email;
        //    oldMemberInfo.userName = newsMemberInfo.userName;
        //    UpdateModel<bigtree.MemberInfo>(oldMemberInfo);
        //    db.SaveChanges();

        //    //db.CreateObjectSet<bigtree.MemberInfo>().ApplyCurrentValues(newsMemberInfo);
        //    //db.SaveChanges();
        //    return View();
        //}


        /// <summary>
        /// 
        /// </summary>
        /// <param name="info">这个info其实你更新的对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Info(MemberDetail info)
        {
            //从实体中查询出一条数据(一个对象)
            var queryUserInfo = db.MemberInfo.Single(x => x.id==info.Id);

            //调用MemberDetail.ConvertToEntity方法对实体对象的字段进行更新。
            var data = MemberDetail.ConvertToEntity(info, queryUserInfo);

            //使用来自控制器的当前值提供程序的值更新指定的模型实例(data)
            UpdateModel<bigtree.MemberInfo>(data);

            //将所有更新保存到数据源并重置对象上下文中的更改跟踪
            db.SaveChanges();

            //db.CreateObjectSet<bigtree.MemberInfo>().ApplyCurrentValues(newsMemberInfo);
            //db.SaveChanges();
            return View();
        }

    }
}

info视图

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/MemberCenter.Master"
     Inherits="System.Web.Mvc.ViewPage<bigtree.ViewModel.MemberDetail>"%>
    <%@ Import Namespace="bigtree" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
        
    <% using (Html.BeginForm()) {%>
    <div class="rightCon">
        <div class="nowTil">
            <h3>
                个人资料</h3>
        </div>
        <ul class="memForm">
            <li>
                <p class="setterTil">
                    手机:</p>
                <div class="setterBd">
                    <%--<input type="text" class="setterInput fl" value=" <%: Model.mobile %>" readonly="">--%>
                    <%: Html.TextBoxFor(x => x.Mobile, new { @class = "setterInput fl" ,@readonly=""})%>
                   
                    <div class="setterExplain">
                        (请填写真实入住人姓名,每间房只填写以为即可)</div>
                </div>
            </li>
            <li>
                <p class="setterTil">
                    姓名:</p>
                <div class="setterBd">
                    <%--<input type="text" class="setterInput fl" value="张小凡" readonly="">--%>
                    <%: Html.TextBoxFor(x => x.Name, new { @class = "setterInput fl"})%>
                </div>
            </li>
            <li>
                <p class="setterTil">
                    邮箱:</p>
                <div class="setterBd">
                    <%--<input type="text" class="setterInput fl">--%>
                    <%: Html.TextBoxFor(x => x.Email, new { @class = "setterInput fl" })%>
                    <div class="setterExplain">
                        未验证</div>
                </div>
            </li>
            <li>
                <p class="setterTil">
                    昵称:</p>
                <div class="setterBd">
                    <%--<input type="text" class="setterInput fl">--%>
                    <%: Html.TextBoxFor(x=>x.UserName,new {@class="setterInput fl"}) %>
                </div>
            </li>
            <li>
                <p class="setterTil">
                    性别:</p>
                <div class="setterBd">
                    <label class="sex">
                      男
                     </label>
                        <%--<input type="radio" name="sex">--%>
                        <%:Html.RadioButtonFor(x=>x.Gender,"1",new {@name="sex"}) %>
                       
                    <label class="sex">
                    女
                    </label>
                       
                        <%:Html.RadioButtonFor(x=>x.Gender,"0" ,new {@name="sex"}) %>
                </div>
            </li>
            
        </ul>
        <input type="submit" value="保存" class="saveBtn">
    </div>
    <% } %>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">

    <script type="text/javascript">
        $(function () {
            $(".navList > :contains('个人资料')").addClass("cur");

        })
    </script>
</asp:Content>

ViewModel 模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace bigtree.ViewModel
{
    public class MemberDetail
    {
        public int Id { get; set; }

        public string Mobile { get; set; }

        public string Name { get; set; }

        public string UserName { get; set; }

        public string Email { get; set; }

        public string Gender { get; set; }

        /// <summary>
        /// 将从实体(数据表)中查询出来的对象转换成ViewModel。其实也就是将从实体中查询出来的对象的属性字段,赋值给ViewModel。然后由ViewModel来将值展示在前端页面。
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static MemberDetail ConvertToViewModel(bigtree.MemberInfo info)
        {
            MemberDetail memberDetail = new MemberDetail();
            memberDetail.Mobile = info.mobile;//将实体的字段赋值给ViewModel对象的字段
            memberDetail.Email = info.email;
            memberDetail.Name = info.name;
            memberDetail.UserName = info.userName;
            memberDetail.Gender = info.sex;
            memberDetail.Id = info.id;
            return memberDetail;  //返回一个ViewModel 字段
        }

        /// <summary>
        /// 将ViewModel转换成实体。首先用户从实体中查询出一条数据(这条数据就是参数bigtree.MemberInfo info),然后我要对这条数据进行更新。这个更新就是用户在前端页TextBox中输入的数据(其实也就是给ViewModel对象的属性赋值的过程)。然后将这个对象的所有属性赋值给从实体中查询出来的对象的对应属性
        /// </summary>
        /// <param name="memberDetail"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public static bigtree.MemberInfo ConvertToEntity(MemberDetail memberDetail, bigtree.MemberInfo info)
        {

            info.email = memberDetail.Email; //将用户在页面输入的Email的值赋值给 实体bigtree.MemberInfo类的email字段,以达到更新实体类(其实这个实体类就是数据表)中的数据
            info.mobile = memberDetail.Mobile;
            info.id = memberDetail.Id;
            info.name = memberDetail.Name;
            info.sex = memberDetail.Gender;
            info.userName = memberDetail.UserName;

            return info; //返回一个更新后的实体对象
        }

    }


}


你可能感兴趣的:(MVC 更新部分字段 (数据库先行))