asp.net MVC2 初探四

简介:
今天教大家如何利用ADO.Net 或者linq实现数据增删改查,新建一个项目
InBlock.gif using System; 
InBlock.gif using System.Collections.Generic; 
InBlock.gif using System.Linq; 
InBlock.gif using System.Data.Linq; 
InBlock.gif using System.Web; 
InBlock.gif using System.Web.Mvc; 
InBlock.gif using System.Data.Linq.Mapping; 
InBlock.gif using MvcApplication1.Models; 
InBlock.gif namespace MvcApplication1.Controllers 
InBlock.gif
InBlock.gif         public  class MovieController : Controller 
InBlock.gif        { 
InBlock.gif                MoviesEntities1 _db =  new MoviesEntities1(); 
InBlock.gif 
InBlock.gif 
InBlock.gif                 public ActionResult Index() 
InBlock.gif                { 
InBlock.gif                        ViewData.Model =  new MoviesEntities1().Movies.ToList(); 
InBlock.gif                         return View(); 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 public ActionResult Details( int id) 
InBlock.gif                { 
InBlock.gif 
InBlock.gif                        var model =  new MoviesEntities1().Movies.First(m => m.ID == id); 
InBlock.gif                         return View(model); 
InBlock.gif                } 
InBlock.gif                 public ActionResult Create() 
InBlock.gif                { 
InBlock.gif                         return View(); 
InBlock.gif                } 
InBlock.gif 
InBlock.gif 
InBlock.gif                [AcceptVerbs(HttpVerbs.Post)] 
InBlock.gif                 public ActionResult Create(Models.Movie m) 
InBlock.gif                { 
InBlock.gif                         try 
InBlock.gif                        { 
InBlock.gif                                _db.AddToMovies(m); 
InBlock.gif                                 if ( string.IsNullOrEmpty(m.Movie_Name)) 
InBlock.gif                                { 
InBlock.gif                                        ModelState.AddModelError( "Movie_Name""电影名称不能为空!"); 
InBlock.gif                                } 
InBlock.gif                                 if (m.Realease_Date ==  null
InBlock.gif                                { 
InBlock.gif                                        ModelState.AddModelError( "Realease_Date""放映时间不能为空"); 
InBlock.gif                                } 
InBlock.gif                                 foreach (Movie mv  in _db.Movies) 
InBlock.gif                                { 
InBlock.gif                                         if (mv.ID == m.ID) 
InBlock.gif                                        { 
InBlock.gif                                                ModelState.AddModelError( "ID""数据库中已经存在Id为" + m.ID +  "的数据"); 
InBlock.gif                                                 break
InBlock.gif                                        } 
InBlock.gif                                } 
InBlock.gif                                 if (ModelState.IsValid) 
InBlock.gif                                { 
InBlock.gif                                        _db.SaveChanges(); 
InBlock.gif                                         return RedirectToAction( "Index"); 
InBlock.gif                                } 
InBlock.gif                                 return View(m); 
InBlock.gif                        } 
InBlock.gif                         catch 
InBlock.gif                        { 
InBlock.gif                                 return View(); 
InBlock.gif                        } 
InBlock.gif 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 public ActionResult Edit( int id) 
InBlock.gif                { 
InBlock.gif 
InBlock.gif                        var movieToUpdate = _db.Movies.First(m => m.ID == id); 
InBlock.gif                        ViewData.Model = movieToUpdate; 
InBlock.gif                         return View(); 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                [AcceptVerbs(HttpVerbs.Post)] 
InBlock.gif                 public ActionResult Edit(FormCollection form) 
InBlock.gif                { 
InBlock.gif 
InBlock.gif                        var id = Int32.Parse(form[ "id"]); 
InBlock.gif                        var movieToUpdate = _db.Movies.First(m => m.ID == id); 
InBlock.gif                        TryUpdateModel(movieToUpdate,  new  string[] {  "Movie_Name""Realease_Date" }, form.ToValueProvider()); 
InBlock.gif                         if (String.IsNullOrEmpty(movieToUpdate.Movie_Name)) 
InBlock.gif                                ModelState.AddModelError( "Movie_Name""Movie_Name is required!"); 
InBlock.gif                         if (movieToUpdate.Realease_Date ==  null
InBlock.gif                                ModelState.AddModelError( "Realease_Date""Realease_Date is required!"); 
InBlock.gif                         if (ModelState.IsValid) 
InBlock.gif                        { 
InBlock.gif                                _db.SaveChanges(); 
InBlock.gif                                 return RedirectToAction( "Index"); 
InBlock.gif                        } 
InBlock.gif                         return View(movieToUpdate); 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 //public ActionResult Delete(int id) 
InBlock.gif                 //{ 
InBlock.gif                 //        try 
InBlock.gif                 //        { 
InBlock.gif                 //                Models.Movie movie = _db.Movies.First(m => m.ID == id); 
InBlock.gif                 //                _db.DeleteObject(movie); 
InBlock.gif                 //                _db.SaveChanges(); 
InBlock.gif                 //                return RedirectToAction("Index"); 
InBlock.gif                 //        } 
InBlock.gif                 //        catch 
InBlock.gif                 //        { 
InBlock.gif                 //                return View("Index"); 
InBlock.gif                 //        } 
InBlock.gif                 //} 
InBlock.gif 
InBlock.gif                 /// <summary> 
InBlock.gif                 /// 使用linq 
InBlock.gif                 /// </summary> 
InBlock.gif                 /// <returns></returns> 
InBlock.gif                 public ActionResult ShowDB() 
InBlock.gif                { 
InBlock.gif                         string str = System.Configuration.ConfigurationManager.ConnectionStrings[ "MoviesConnectionString"].ToString(); 
InBlock.gif                        DataContext MyDataSource =  new DataContext(str); 
InBlock.gif                        Table<Movies> tb = MyDataSource.GetTable<Movies>(); 
InBlock.gif                        IQueryable<Movies> MyQuery = from movies  in tb where movies.ID >= 5 select movies; 
InBlock.gif                         return View(MyQuery); 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 public ActionResult Delete( int id) 
InBlock.gif                { 
InBlock.gif                        DataClasses1DataContext DataC1Context =  new DataClasses1DataContext(); 
InBlock.gif                        Movy mv = DataC1Context.Movies.First(c => c.ID == id); 
InBlock.gif                        DataC1Context.Movies.DeleteOnSubmit(mv); 
InBlock.gif                        DataC1Context.SubmitChanges(); 
InBlock.gif                         return RedirectToRoute( "start"); 
InBlock.gif                } 
InBlock.gif        } 
InBlock.gif        [Table(Name =  "Movies")] 
InBlock.gif         public  class Movies 
InBlock.gif        { 
InBlock.gif                 private  int _ID; 
InBlock.gif                 private  string _Movie_Name; 
InBlock.gif                 private DateTime _Realease_Date; 
InBlock.gif                [Column(Storage =  "_ID"
InBlock.gif                AutoSync = AutoSync.OnInsert, 
InBlock.gif                DbType =  "int not null indentity"
InBlock.gif                IsPrimaryKey =  true
InBlock.gif                IsDbGenerated =  true
InBlock.gif                ] 
InBlock.gif                 public  int ID 
InBlock.gif                { 
InBlock.gif                        set { _ID = ID; } 
InBlock.gif                        get {  return  this._ID; } 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                [Column(Storage =  "_Movie_Name"
InBlock.gif                        AutoSync = AutoSync.Always, 
InBlock.gif                        DbType =  "varchar(200) not null"
InBlock.gif                        IsDbGenerated =  true 
InBlock.gif                        )] 
InBlock.gif                 public  string Movie_Name 
InBlock.gif                { 
InBlock.gif                        set { _Movie_Name = Movie_Name; } 
InBlock.gif                        get {  return  this._Movie_Name; } 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                [Column(Storage =  "_Realease_Date"
InBlock.gif                        AutoSync = AutoSync.Always, 
InBlock.gif                        DbType =  "datetime not null"
InBlock.gif                        IsDbGenerated =  true 
InBlock.gif                        )] 
InBlock.gif 
InBlock.gif                 public DateTime Realease_Date 
InBlock.gif                { 
InBlock.gif                        set { _Realease_Date = Realease_Date; } 
InBlock.gif                        get {  return _Realease_Date; } 
InBlock.gif                } 
InBlock.gif        } 
InBlock.gif 
InBlock.gif}
上述代码咋一看去很郁闷。其实和日常的webForm是一样的。首先在Index上单击右键Create一个View,那么这个action方法Index对应的页面就是你所建的View。ViewData.Model = new MoviesEntities1().Movies.ToList();将一个List数据泛型返回给ViewData。ViewData作用类似于ViewState,只能在特定的一个视图使用。而TempData作用类似于session。但是其在controller中只能传递使用一次,之后就会被销毁。所以上述代码就是向视图页面Index.aspx页面发送一组数据。
InBlock.gif<%@ Page Title= "" Language="C# " MasterPageFile="~/Views/Shared/Site.Master " Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Movie>>" %> 
InBlock.gif 
InBlock.gif<asp:Content ID= "Content1" ContentPlaceHolderID= "TitleContent" runat= "server"
InBlock.gif        Index 
InBlock.gif</asp:Content> 
InBlock.gif<asp:Content ID= "Content2" ContentPlaceHolderID= "MainContent" runat= "server"
InBlock.gif        <h2> 
InBlock.gif                Index</h2> 
InBlock.gif        <table> 
InBlock.gif                <tr> 
InBlock.gif                        <th> 
InBlock.gif                        </th> 
InBlock.gif                        <th> 
InBlock.gif                                ID 
InBlock.gif                        </th> 
InBlock.gif                        <th> 
InBlock.gif                                Movie_Name 
InBlock.gif                        </th> 
InBlock.gif                        <th> 
InBlock.gif                                Realease_Date 
InBlock.gif                        </th> 
InBlock.gif                </tr> 
InBlock.gif                <%  foreach (var item  in Model) 
InBlock.gif                     { %> 
InBlock.gif                <tr> 
InBlock.gif                        <td> 
InBlock.gif                                <%: item.ID %> 
InBlock.gif                        </td> 
InBlock.gif                        <td> 
InBlock.gif                                <%: item.Movie_Name %> 
InBlock.gif                        </td> 
InBlock.gif                        <td> 
InBlock.gif                                <%: String.Format( "{0:g}", item.Realease_Date) %> 
InBlock.gif                        </td> 
InBlock.gif                        <td> 
InBlock.gif                                <%: Html.ActionLink( "Edit""Edit"new { id=item.ID }) %> 
InBlock.gif                                | 
InBlock.gif                                <%: Html.ActionLink( "Details""Details"new { id=item.ID })%> 
InBlock.gif                                | 
InBlock.gif                                <%: Html.ActionLink( "Delete""Delete"new { id=item.ID })%> 
InBlock.gif                        </td> 
InBlock.gif                </tr> 
InBlock.gif                <% } %> 
InBlock.gif        </table> 
InBlock.gif        <p> 
InBlock.gif                <%: Html.ActionLink( "Create New""Create") %> 
InBlock.gif                <%: Html.ActionLink( "跳转到筛选的页面""ShowDB")%> 
InBlock.gif        </p> 
InBlock.gif</asp:Content>
在这个Html页面,当接收到传过来的数据的时候进行循环遍历,采用HtmlHelper扩展类进行显示。 <%: Html.ActionLink("跳转到筛选的页面", "ShowDB")%>这句的意思是一个超链接,连接到ShowDB这个Action。showDB再调用return view跳转到ShowDb.aspx。
 public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(Models.Movie m){
}
这段代码一个是post方式,另一个是get方式,所谓Get方式即xxx.aspx?id=xx。所以第一个Create所做的动作就是当你点击添加的时候,出现一个添加页面(Create.aspx)而已,仅此而已。第二个post方式的Create才是真正的添加,首先你做个简单的验证。如果验证通过。则调用_db.SaveChanges();在这里需要说明的是Models.Movie m参数的值自动从添加页面可以自动获取。无需写任何代码。对于修改比较特殊,主键不用显示页面view如下
< %@ Page  Title ="" Language="C#"  MasterPageFile ="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.Movie >" %> 

< asp:Content  ID ="Content1"  ContentPlaceHolderID ="TitleContent"  runat ="server" > 
        Edit 
</asp:Content> 
< asp:Content  ID ="Content2"  ContentPlaceHolderID ="MainContent"  runat ="server" > 
         < h2 > 
                Edit </h2> 
        <% using (Html.BeginForm()) 
             {%> 
         < %: Html.ValidationSummary(true) % > 
         < fieldset > 
                 < legend >Fields </legend> 
                 < div > 
                         < %: Html.HiddenFor(model = > model.ID)%> 
                 </div> 
                 < div  class ="editor-label" > 
                         < %: Html.LabelFor(model = > model.Movie_Name) %> 
                 </div> 
                 < div  class ="editor-field" > 
                         < %: Html.TextBoxFor(model = > model.Movie_Name) %> 
                         < %: Html.ValidationMessageFor(model = > model.Movie_Name) %> 
                 </div> 
                 < div  class ="editor-label" > 
                         < %: Html.LabelFor(model = > model.Realease_Date) %> 
                 </div> 
                 < div  class ="editor-field" > 
                         < %: Html.TextBoxFor(model = > model.Realease_Date, String.Format("{0:g}", Model.Realease_Date)) %> 
                         < %: Html.ValidationMessageFor(model = > model.Realease_Date) %> 
                 </div> 
                 < p > 
                         < input  type ="submit"  value ="保存"  /> 
                 </p> 
         </fieldset> 
         < % } % > 
         < div > 
                 < %: Html.ActionLink("返回", "Index") % > 
         </div> 
</asp:Content> 
 

本文转自 BruceAndLee 51CTO博客,原文链接:http://blog.51cto.com/leelei/318427,如需转载请自行联系原作者

相关文章
|
3月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
40 0
|
1月前
|
开发框架 前端开发 .NET
进入ASP .net mvc的世界
进入ASP .net mvc的世界
28 0
|
1月前
mvc.net分页查询案例——mvc-paper.css
mvc.net分页查询案例——mvc-paper.css
5 0
|
1月前
|
开发框架 前端开发 .NET
C# .NET面试系列六:ASP.NET MVC
<h2>ASP.NET MVC #### 1. MVC 中的 TempData\ViewBag\ViewData 区别? 在ASP.NET MVC中,TempData、ViewBag 和 ViewData 都是用于在控制器和视图之间传递数据的机制,但它们有一些区别。 <b>TempData:</b> 1、生命周期 ```c# TempData 的生命周期是短暂的,数据只在当前请求和下一次请求之间有效。一旦数据被读取,它就会被标记为已读,下一次请求时就会被清除。 ``` 2、用途 ```c# 主要用于在两个动作之间传递数据,例如在一个动作中设置 TempData,然后在重定向到另
95 5
|
3月前
|
XML 前端开发 定位技术
C#(NET Core3.1 MVC)生成站点地图(sitemap.xml)
C#(NET Core3.1 MVC)生成站点地图(sitemap.xml)
25 0
|
3月前
|
前端开发
.net core mvc获取IP地址和IP所在地(其实是百度的)
.net core mvc获取IP地址和IP所在地(其实是百度的)
123 0
|
5月前
|
开发框架 自然语言处理 前端开发
基于ASP.NET MVC开发的、开源的个人博客系统
基于ASP.NET MVC开发的、开源的个人博客系统
51 0
|
8月前
|
SQL 开发框架 前端开发
[回馈]ASP.NET Core MVC开发实战之商城系统(完:内附源码)
经过一段时间的准备,【ASP.NET Core MVC开发实战之商城系统】已经完成,目前代码已开发完成,先将全部内容整理分享,如有不足之处,还请指正。
106 0
|
8月前
|
开发框架 前端开发 .NET
[回馈]ASP.NET Core MVC开发实战之商城系统(六)
经过一段时间的准备,新的一期【ASP.NET Core MVC开发实战之商城系统】已经开始,在之前的文章中,讲解了商城系统的整体功能设计,页面布局设计,环境搭建,系统配置,及首页【商品类型,banner条,友情链接,降价促销,新品爆款】,商品列表页面,商品详情,购物车等功能的开发,今天继续讲解订单管理功能开发,仅供学习分享使用,如有不足之处,还请指正。
214 0