mvc

1.E-F(Entity Framework)  只是实现ORM的框架之一
    
2.ORM:思想  表实体和表的相互转换
   
    表实体的变化展现在表中   将表中的变化反映到表实体中
 
    通过实例展示EF:
        1.创建控制台应用程序(EFDemo)
        2.添加ADO.NET实体数据模型 (Model1.edmx)
        3.在main中添加如下代码,实现增加数据:
             //做一个添加操作
            //1、声明一个EF的上下文
            bjhksjEntities dbContext = new bjhksjEntities();

            //声明一个User实体
            HKSJ_USERS user = new HKSJ_USERS();
            user.LoginName = "dhakdh";
            user.Mail = "hdkadk";
            user.PassWord = "dadaad";
            user.Plane = "dhahdkah";
            user.UserName = "wwz";
            user.cardNo = "adad";
            user.phone = "aiodiod";

            //3.告诉EF咱们对上面的实体做一个插入操作
            dbContext.HKSJ_USERS.AddObject(user);

            //4.告诉上下文把实体的变化保存到数据库里面去
            dbContext.SaveChanges();

            Console.ReadKey();
            
        以上代码即可实现在User表中增加数据
        
3.协变:把子类的泛型集合赋值给父类泛型集合。这样会更安全,因为不能访问子类的元素了
  逆变:把父类的泛型集合赋值给子类的泛型集合。传入参数的时候是逆变,返回值的时候是协变。也是为了安全、
 

4.MVC:
    他出现的目的不是取代WebForm开发,只是另一种方式。
    
    mvc三层模式:
        aspx(html)页面                                                            View层
        代码后置类的控制逻辑
            调用业务逻辑。处理用户的请求数据,把数据交给view                   Controller层
        
        业务逻辑层 数据访问层 数据模型层                                         Model层

    调用方式:用户---->Controller------->Model------>DB----->Model------->Controller------>View-------->用户
    
    WebForm中,.aspx就相当于MVC的View,.aspx.cs就相当于MVC的Controller
        但是区别是:在Webform中,不能讲后天控制器和页面完全隔离,但是MVC能做的很好
        
        前台用span标签可以降低耦合度,如:<span><%= LbText></span>   后台只需要定义LbText属性就可以进行操作
    
    WebForm中优点是:事件响应模式   ViewState   页面生命周期
    
    一般处理程序+html:效率最高
    
     Ajax+一般处理程序+json(天然跟js没有隔阂,比xml或者是html传递数据更小,也是跨平台的)
    
     MVC+Ajax+json
    
     172.16.12.1001
     172.16.2.12   100  admin ej123456
     1.Controller的实现:以Controller结尾;必须非静态类;实现IController接口
       Controller中的方法都成为Action
       
       
      WebForm中用户请求的页面是Aspx页面
      mvc中用户请求的是Controller里面的方法  不要将Views文件下的aspx页面设为启动页
      Controller的三个在指责:处理用户请求(Requeat Response); 调用业务逻辑;将数据传给View进行展示(ViewData)
      Controller中的方法如果没有指定视图,则默认会访问相应文件夹下的Index视图,如果需要改变,则使用View("Demo2");尽量将action             视图名字与视图中保持一致。
                   首先搜索相应文件夹下的视图,如果没有找到则到Shared文件下查找
    
    
      Global.asax:其内包含Application_Start()方法,该方法主要是进行初始化,一次页面加载只执行一次。
                  方法内的RouteConfig的静态方法,该方法在App_start内,里面还有请求页面的url地址
                  
                  
      注意:页面调试的时候,在URL中输入的地址和在App_start内,里面还有请求页面的url地址必须相一致。可在认为在电脑中输入:
             eg:http://localhost:12981/Home/Index  Home为Controller,Index为Action方法,注意后面不带任何的后缀。
            
      
      如何在Controller中实现页面的跳转以及数据的传输:
        例如一个用户注册页面,其注意事项如下:
            1.Form表单中,action="/Controller名称/Action方法名" method="post"
            2.增加处理用户注册的方法,
                如何接收表单中的内容呢:1.string name=Request["txtName"];
                                          return Content("ok"+name);//该语句相当于使用了:Response.Write("ok"+name); Response.End();
                                        
                                        2.可在方法中添加参数,如下:
                                            public ActionResult ProcessUserRegist(FormCollection collection)
                                          用下面的方法来接收数据:
                                            string name=collection["txtName"];
                                            
                                        总结:上面两种方法的区别是:
                                            在Form表单内,mathod="get"时,第一种方法运行后的结果是,url中有提交的相关信息,并且返回了ok+。。。。;第二种方法,则url中没有表单提交的详细内容,同时也不能返回name的内容,只是返回了ok。
                                            
                                            在form表单中,method="post"时,两种方法url中都没有详细的信息。
                                                第一种方法返回的结果就是ok加上提交过来的name的值。
                                                第二种方法返回的结果和第一种方法完全一致。
                                                
                                                
                                        3.方法参数为 public ActionResult ProcessUserRegist(string txtName,string txtPwd)
                                           
                                            return Content("ok"+txtName);
                                            
                                        注意:这种方法,传递的参数必须与前台页面中的name相一致,这样才能正确匹配。
                                        
            在aspx页面中查看源代码,可以发现,其与我们编写的几乎完全一样,非常干净,增加了效率。
            
            
            完整的用户注册代码:
                namespace MvcApplication1.Controllers
                    {
                        public class UserInfoController : Controller
                        {
                            //
                            // GET: /UserInfo/

                            public ActionResult Index()
                            {
                                return View();
                            }
                            public ActionResult UserRegist()
                            {
                                return View();
                            }
                            public ActionResult ProcessUserRegist(string txtName,string txtPwd)//FormCollection collection
                            {
                                //如何拿到用户提交来的内容呢?
                                //string name = Request["txtName"];
                                //string name = collection["txtName"];
                                return Content("ok" + txtName);//Return Content相当于Response.write(); Response.End(); 实现的功能是往前台输出一个字符串
                               
                            }
                        }
                    }
                    
                    
                <body>
                    <div>
                      <form action="/UserInfo/ProcessUserRegist" method="get">
                         <table>
                            <tr>
                              <td>用户名:</td><td><input type="text" name="txtName"/></td>
                            </tr>
                            <tr>
                              <td>密码:</td><td><input type="text" name="txtPwd"/></td>
                            </tr>
                            <tr>
                               <td colspan="2">
                                  <input type="submit" value="提交"/>
                               </td>
                            </tr>
                         </table>
                      </form>
                    </div>
                </body>

    2.HtmlHelper方法:
        问题:如果存在一个超链接,普通格式如下:<a href="/UserInfo/UserRegist">普通连接到用户注册页面</a>,这种格式请求访问时是根据
              RouteConfig的静态方法的url格式相一致。如果,路由Url方式发生改变,则会带来很大的麻烦。
        
        解决方案1:<a href="<%= Url.Action("UserRegist","UserInfo") %>">Url.Action实现连接</a><%--
                    Url中的U必须大写,参数内前面是Action方法,后面是Controller--%>    
                            
        实现方案2:  <%= Html.ActionLink("超级链接文本","UserRegist","UserInfo")%>
                     <%= Html.ActionLink("超级链接文本2", "UserRegist", "UserInfo", new { demo = "sssss", mm = "defada" }, new {style="color:Red",id=33,@class="sfdffdsfsd"})%>
                    
                    
        问题:mvc中不能像webform中那样拖拽控件:
        
        解决方案:<%= Html.DropDownList("CityList") %>
        
                   ViewData["CityList"] = new List<SelectListItem>()
                    {
                        new SelectListItem(){Selected=true,Text="Beijing",Value="1"},
                        new SelectListItem(){Selected=false,Text="uzhou",Value="2"},
                        new SelectListItem(){Selected=false,Text="nanjing",Value="3"}
                    };
                
                
                 <%= Html.TextBox("sss") %>
                  ViewData["sss"] = "DADAD";
                  
        问题:如何实现自定义Html扩展方法:本质就是静态类,静态方法,使用this关键字
        解决方案:添加一个类(可以在Modles中实现),MyHtmlHelper.cs
                  namespace System.Web.Mvc//一般情况下,把扩展方法所在的命名空间跟要扩展类型的 命名空间相一致
                    {
                        public static class MyHtmlHelper
                        {
                            public static string MyLabel(this HtmlHelper helper, string lbText)
                            {
                                return string.Format("<span>{0}</span>",lbText);
                            }
                        }
                    }
                    <%= Html.MyLabel("abcd")%>
            注意:为了实现调用自定义扩展方法的灵活性:将命名空间名称改为和系统一样的即可。
            
        <%= %>表示直接输出
        <%: %>表示先对后面的内容Encode,再输出
        
        出于安全考虑,应该使用<%: %>,如果将自定义扩展方法的的返回类型改为MvcHtmlString类型,就不会Encoding.
                            public static MvcHtmlString MyLabel(this HtmlHelper helper, string lbText)
                            {
                                return string.Format("<span>{0}</span>",lbText);
                            }
                            
                            <%: Html.MyLabel("abcd")%>
        HtmlHelper中遇到MvcHtmlString时,不进行编码化处理                
        自定义扩展方法的好处:
            可是随时根据需求进行相应的更改,而不需要大量的操作。
            在已有的类型上扩展方法。
            
    3.弱类型页面:
        
        1.首先添加一个类,可以在Models中创建Customer.cs:
             public class Customer
                {
                    public string SName { get; set; }
                    public int Id { get; set; }
                    public int Age { get; set; }
                    public string Email { get; set; }
                }
        2.创建一个Controller:CustomerController.cs,并且添加了一个视图Views:ShowCustomer.aspx
        
        3.在CustomerController.cs中添加Action方法如下:
            public ActionResult ShowCustomer(int id)
            {
               //根据id值获取当前的Customer
               
               Customer customer=new Customer(){Id=id,Age=12,Email="gugtyu@hd.com",SName="wang"};
               ViewData["Customer"]=customer;
               return View();
            }
            
        4.在ShowCustomer.aspx中:
              <div>
                 <% var customer = ViewData["Customer"] as Customer;%>
                 <table>
                   <tr>
                     <td>顾客名:</td><td><%= customer.SName %></td>
                   </tr>
                   <tr>
                     <td>顾客年龄:</td><td><%= customer.Age %></td>
                   </tr>
                   <tr>
                     <td>顾客邮箱:</td><td><%= customer.Email %></td>
                   </tr>
                   <tr>
                     <td>顾客Id:</td><td><%= customer.Id %></td>
                   </tr>
                 </table>
                </div>
                
    4.强类型页面:
        1.首先添加一个类,可以在Models中创建Customer.cs:
             public class Customer
                {
                    public string SName { get; set; }
                    public int Id { get; set; }
                    public int Age { get; set; }
                    public string Email { get; set; }
                }
        2.创建一个Controller:CustomerController.cs,并且添加了一个视图Views:Detail.aspx
        
        3.在CustomerController.cs中添加Action方法如下:
               public ActionResult Detail(int id)
                {
                    Customer customer = new Customer() { Id = id, Age = 12, Email = "daj@djkaj.com", SName = "dhajh" };
                    ViewData.Model = customer;
                    return View();
                }
        
        4.在Detail.aspx中:
            <div>
               <table>
               <tr>
                 <td>顾客名:</td><td><%: Model.SName %></td>
                 <%: Html.TextBox("Id") %>
                 <%: Html.TextBoxFor(c=>c.Id) %>
               </tr>
               <tr>
                 <td>顾客年龄:</td><td><%: Model.Age %></td>
               </tr>
               <tr>
                 <td>顾客邮箱:</td><td><%: Model.Email %></td>
               </tr>
               <tr>
                 <td>顾客Id:</td><td><%: Model.Id %></td>
               </tr>
             </table>
            </div>
            
        注意:在此页面如果想要真正实行强类型页面,则需要将<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.Customer>" %>
        
        
    5.实现增删改查:
    
      一:显示信息的功能实现
        1.创建ado.net 实体数据类型
        2.创建Controller:ClassInfoController
        
          添加如下代码:
            
            bjhksjEntities dbContext = new bjhksjEntities();
            public ActionResult Index()
            {
                ViewData.Model = dbContext.HKSJ_USERS.AsEnumerable();
                return View();
            }
        3.添加强类型视图:Index.aspx(视图数据根据实体数据类型选择,视图内容选择list),及显示信息的功能已经完成。
      
      
      二:显示详细信息的功能:
        1.在ClassInfoController.cs中添加如下代码:
            public ActionResult Detail(int id)
            {
                //ViewData.Model = dbContext.HKSJ_USERS.Find(id);
                ViewData.Model = dbContext.HKSJ_USERS.Where(u=>u.ID==id).FirstOrDefault();
                return View();
            }
            
        2.添加View:Detail.aspx
            
        视图数据根据实体数据类型选择,视图内容选择Detail)
        
      
      三:删除功能的实现:
        1.在ClassInfoController.cs中添加如下代码:
             public ActionResult Delete(int id)
            {
                ViewData.Model = dbContext.HKSJ_USERS.Where(u=>u.ID==id).FirstOrDefault();
                return View();
            }

            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
                {
                 //把数据删除
                HKSJ_USERS userInfo = new HKSJ_USERS();
                userInfo.ID = id;
                userInfo.LoginName = string.Empty;
                userInfo.Mail = string.Empty;
                userInfo.PassWord = string.Empty;
                userInfo.phone = string.Empty;
                userInfo.Plane = string.Empty;

                dbContext.HKSJ_USERS.Attach(userInfo);
                dbContext.entry(userInfo).State = EntityState.Deleted;
                dbContext.SaveChanges();

                return RedirectToAction("Index");
            }
        
        2.添加View:Delelte.aspx
            
        视图数据根据实体数据类型选择,视图内容选择Delelte)
        
        
      四:增加功能的实现:
         
        1.在ClassInfoController.cs中添加如下代码:
         public ActionResult Add()
            {
               
                return View();
            }

            [HttpPost]
            public ActionResult Add(HKSJ_USERS userInfo)
            {
                dbContext.HKSJ_USERS.Add(userInfo);
                dbContext.SaveChanges();
                return RedirectToAction("Index");
            }    
        2.添加View:Add.aspx
            
        视图数据根据实体数据类型选择,视图内容选择Create)    
        
       
       五:修改功能的实现:
        1.在ClassInfoController.cs中添加如下代码:
         public ActionResult Edit(int id)
        {
            ViewData.Model = dbContext.HKSJ_USERS.Where(u=>u.ID==id).FirstOrDefault();
            return View();
        }

        [HttpPost]
        public ActionResult Edit(int id,HKSJ_USERS userInfo)
        {
            dbContext.Entry(userInfo).State=EntityState.Modified;
            dbContext.SaveChanges();
            return RedirectToAction("Index");
        }    
        
        
        2.添加View:Edit.aspx
            
        视图数据根据实体数据类型选择,视图内容选择Edit)    
        
        
    6.实现分页:
        1.在HtmlHelper.cs内添加如下代码:
             //主要就是输出分页的超级链接的标签
        //自定义分页Helper扩展
        public static HtmlString ShowPageNavigate(this HtmlHelper htmlHelper, int currentPage, int pageSize, int totalCount)
        {
            var redirectTo = htmlHelper.ViewContext.RequestContext.HttpContext.Request.Url.AbsolutePath;
            pageSize = pageSize == 0 ? 3 : pageSize;
            var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //总页数
            var output = new StringBuilder();
            if (totalPages > 1)
            {
                //if (currentPage != 1)
                {//处理首页连接
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex=1&pageSize={1}'>首页</a> ", redirectTo, pageSize);
                }
                if (currentPage > 1)
                {//处理上一页的连接
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>上一页</a> ", redirectTo, currentPage - 1, pageSize);
                }
                else
                {
                    // output.Append("<span class='pageLink'>上一页</span>");
                }

                output.Append(" ");
                int currint = 5;
                for (int i = 0; i <= 10; i++)
                {//一共最多显示10个页码,前面5个,后面5个
                    if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages)
                    {
                        if (currint == i)
                        {//当前页处理
                            //output.Append(string.Format("[{0}]", currentPage));
                            output.AppendFormat("<a class='cpb' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage, pageSize, currentPage);
                        }
                        else
                        {//一般页处理
                            output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage + i - currint, pageSize, currentPage + i - currint);
                        }
                    }
                    output.Append(" ");
                }
                if (currentPage < totalPages)
                {//处理下一页的链接
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>下一页</a> ", redirectTo, currentPage + 1, pageSize);
                }
                else
                {
                    //output.Append("<span class='pageLink'>下一页</span>");
                }
                output.Append(" ");
                if (currentPage != totalPages)
                {
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>末页</a> ", redirectTo, totalPages, pageSize);
                }
                output.Append(" ");
            }
            output.AppendFormat("第{0}页 / 共{1}页", currentPage, totalPages);//这个统计加不加都行

            return new HtmlString(output.ToString());
        }
        
        
        2.在Action  Index方法中:添加如下代码:
             public ActionResult Index(int pageIndex=1,int pageSize=2)
        {
            //ViewData.Model = dbContext.HKSJ_USERS.AsEnumerable();

            ViewData["pageIndex"] = pageIndex;
            ViewData["pageSize"] = pageSize;
            ViewData["count"] = dbContext.HKSJ_USERS.Count();

            ViewData.Model = dbContext.HKSJ_USERS
                                    .OrderBy(u => u.ID)
                                    .Skip(pageSize * (pageIndex - 1))
                                    .Take(pageSize).AsEnumerable();
            return View();

        }
        
Ajax:
    1.首先创建一个Controller:AjaxController.cs
    2.然后创建一个视图 index.aspx
    3.传统的异步实现:
        在index.aspx中添加如下代码:
            <input type="button" value="获取时间" id="btnJQAjax"/>
            
            
        在头部:
            <script type="text/JavaScript">
              $(function(){
                 $("#btnJQAjax").click(function(){
                     $.ajax(
                     {
                        url:"/Ajax/Index",
                        type:"post",
                        data:{},
                        function(data){
                            alert(data);
                        }
                     });
                 });
              });
            </script>
        在AjaxController.cs中添加如下代码:
            public ActionResult Index()
            {
                 return Content(new Date().ToString());
            }
            
        由以上步骤就可以实现传统的异步请求!
        
    4.MVC自带的异步请求:
        1.基本步骤通以上传统的实现的方式相一致。
        2.在Index.aspx中添加如下代码:
            
            function afterSuccess(data){
               alert(data);
            }
            $("#loadingDiv").css("display","none");
             <% using(Ajax.BeginForm("Date","Ajax",new AjaxOption()
             {
                Confirm="您确认要提交吗",
                HttpMethod="Post",
                UpdateTargetId="ResultDiv",
                InsertionMode=InsertionMode.Replace,
                OnSucess="afterSuccess",
                LoadingElemtId="loadingDiv"
             })
             {%>
                <input type="text" name="txtName"/>
                <br/>
                <input type="submit" value="获取时间"/>
             <%}%>
            
             <div id="ResultDiv"></div>
             <div id="loadingDiv"><img........./></div>
            
             如果觉得太快,可是在Date方法中,添加如下代码:Thread.Sleep(3000);
   
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值