asp.net MVC2 初探四

简介:
今天教大家如何利用ADO.Net 或者linq实现数据增删改查,新建一个项目
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Data.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Data.Linq.Mapping; 
using MvcApplication1.Models; 
namespace MvcApplication1.Controllers 

         public  class MovieController : Controller 
        { 
                MoviesEntities1 _db =  new MoviesEntities1(); 
 
 
                 public ActionResult Index() 
                { 
                        ViewData.Model =  new MoviesEntities1().Movies.ToList(); 
                         return View(); 
                } 
 
                 public ActionResult Details( int id) 
                { 
 
                        var model =  new MoviesEntities1().Movies.First(m => m.ID == id); 
                         return View(model); 
                } 
                 public ActionResult Create() 
                { 
                         return View(); 
                } 
 
 
                [AcceptVerbs(HttpVerbs.Post)] 
                 public ActionResult Create(Models.Movie m) 
                { 
                         try 
                        { 
                                _db.AddToMovies(m); 
                                 if ( string.IsNullOrEmpty(m.Movie_Name)) 
                                { 
                                        ModelState.AddModelError( "Movie_Name""电影名称不能为空!"); 
                                } 
                                 if (m.Realease_Date ==  null
                                { 
                                        ModelState.AddModelError( "Realease_Date""放映时间不能为空"); 
                                } 
                                 foreach (Movie mv  in _db.Movies) 
                                { 
                                         if (mv.ID == m.ID) 
                                        { 
                                                ModelState.AddModelError( "ID""数据库中已经存在Id为" + m.ID +  "的数据"); 
                                                 break
                                        } 
                                } 
                                 if (ModelState.IsValid) 
                                { 
                                        _db.SaveChanges(); 
                                         return RedirectToAction( "Index"); 
                                } 
                                 return View(m); 
                        } 
                         catch 
                        { 
                                 return View(); 
                        } 
 
                } 
 
                 public ActionResult Edit( int id) 
                { 
 
                        var movieToUpdate = _db.Movies.First(m => m.ID == id); 
                        ViewData.Model = movieToUpdate; 
                         return View(); 
                } 
 
                [AcceptVerbs(HttpVerbs.Post)] 
                 public ActionResult Edit(FormCollection form) 
                { 
 
                        var id = Int32.Parse(form[ "id"]); 
                        var movieToUpdate = _db.Movies.First(m => m.ID == id); 
                        TryUpdateModel(movieToUpdate,  new  string[] {  "Movie_Name""Realease_Date" }, form.ToValueProvider()); 
                         if (String.IsNullOrEmpty(movieToUpdate.Movie_Name)) 
                                ModelState.AddModelError( "Movie_Name""Movie_Name is required!"); 
                         if (movieToUpdate.Realease_Date ==  null
                                ModelState.AddModelError( "Realease_Date""Realease_Date is required!"); 
                         if (ModelState.IsValid) 
                        { 
                                _db.SaveChanges(); 
                                 return RedirectToAction( "Index"); 
                        } 
                         return View(movieToUpdate); 
                } 
 
                 //public ActionResult Delete(int id) 
                 //{ 
                 //        try 
                 //        { 
                 //                Models.Movie movie = _db.Movies.First(m => m.ID == id); 
                 //                _db.DeleteObject(movie); 
                 //                _db.SaveChanges(); 
                 //                return RedirectToAction("Index"); 
                 //        } 
                 //        catch 
                 //        { 
                 //                return View("Index"); 
                 //        } 
                 //} 
 
                 /// <summary> 
                 /// 使用linq 
                 /// </summary> 
                 /// <returns></returns> 
                 public ActionResult ShowDB() 
                { 
                         string str = System.Configuration.ConfigurationManager.ConnectionStrings[ "MoviesConnectionString"].ToString(); 
                        DataContext MyDataSource =  new DataContext(str); 
                        Table<Movies> tb = MyDataSource.GetTable<Movies>(); 
                        IQueryable<Movies> MyQuery = from movies  in tb where movies.ID >= 5 select movies; 
                         return View(MyQuery); 
                } 
 
                 public ActionResult Delete( int id) 
                { 
                        DataClasses1DataContext DataC1Context =  new DataClasses1DataContext(); 
                        Movy mv = DataC1Context.Movies.First(c => c.ID == id); 
                        DataC1Context.Movies.DeleteOnSubmit(mv); 
                        DataC1Context.SubmitChanges(); 
                         return RedirectToRoute( "start"); 
                } 
        } 
        [Table(Name =  "Movies")] 
         public  class Movies 
        { 
                 private  int _ID; 
                 private  string _Movie_Name; 
                 private DateTime _Realease_Date; 
                [Column(Storage =  "_ID"
                AutoSync = AutoSync.OnInsert, 
                DbType =  "int not null indentity"
                IsPrimaryKey =  true
                IsDbGenerated =  true
                ] 
                 public  int ID 
                { 
                        set { _ID = ID; } 
                        get {  return  this._ID; } 
                } 
 
                [Column(Storage =  "_Movie_Name"
                        AutoSync = AutoSync.Always, 
                        DbType =  "varchar(200) not null"
                        IsDbGenerated =  true 
                        )] 
                 public  string Movie_Name 
                { 
                        set { _Movie_Name = Movie_Name; } 
                        get {  return  this._Movie_Name; } 
                } 
 
                [Column(Storage =  "_Realease_Date"
                        AutoSync = AutoSync.Always, 
                        DbType =  "datetime not null"
                        IsDbGenerated =  true 
                        )] 
 
                 public DateTime Realease_Date 
                { 
                        set { _Realease_Date = Realease_Date; } 
                        get {  return _Realease_Date; } 
                } 
        } 
 
}
上述代码咋一看去很郁闷。其实和日常的webForm是一样的。首先在Index上单击右键Create一个View,那么这个action方法Index对应的页面就是你所建的View。ViewData.Model = new MoviesEntities1().Movies.ToList();将一个List数据泛型返回给ViewData。ViewData作用类似于ViewState,只能在特定的一个视图使用。而TempData作用类似于session。但是其在controller中只能传递使用一次,之后就会被销毁。所以上述代码就是向视图页面Index.aspx页面发送一组数据。
<%@ Page Title= "" Language="C# " MasterPageFile="~/Views/Shared/Site.Master " Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Movie>>" %> 
 
<asp:Content ID= "Content1" ContentPlaceHolderID= "TitleContent" runat= "server"
        Index 
</asp:Content> 
<asp:Content ID= "Content2" ContentPlaceHolderID= "MainContent" runat= "server"
        <h2> 
                Index</h2> 
        <table> 
                <tr> 
                        <th> 
                        </th> 
                        <th> 
                                ID 
                        </th> 
                        <th> 
                                Movie_Name 
                        </th> 
                        <th> 
                                Realease_Date 
                        </th> 
                </tr> 
                <%  foreach (var item  in Model) 
                     { %> 
                <tr> 
                        <td> 
                                <%: item.ID %> 
                        </td> 
                        <td> 
                                <%: item.Movie_Name %> 
                        </td> 
                        <td> 
                                <%: String.Format( "{0:g}", item.Realease_Date) %> 
                        </td> 
                        <td> 
                                <%: Html.ActionLink( "Edit""Edit"new { id=item.ID }) %> 
                                | 
                                <%: Html.ActionLink( "Details""Details"new { id=item.ID })%> 
                                | 
                                <%: Html.ActionLink( "Delete""Delete"new { id=item.ID })%> 
                        </td> 
                </tr> 
                <% } %> 
        </table> 
        <p> 
                <%: Html.ActionLink( "Create New""Create") %> 
                <%: Html.ActionLink( "跳转到筛选的页面""ShowDB")%> 
        </p> 
</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,如需转载请自行联系原作者

相关文章
|
2月前
|
开发框架 前端开发 JavaScript
ASP.NET MVC 教程
ASP.NET 是一个使用 HTML、CSS、JavaScript 和服务器脚本创建网页和网站的开发框架。
42 7
|
2月前
|
存储 开发框架 前端开发
ASP.NET MVC 迅速集成 SignalR
ASP.NET MVC 迅速集成 SignalR
59 0
|
3月前
|
开发框架 前端开发 .NET
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
49 0
|
3月前
|
开发框架 前端开发 安全
ASP.NET MVC 如何使用 Form Authentication?
ASP.NET MVC 如何使用 Form Authentication?
|
3月前
|
开发框架 .NET
Asp.Net Core 使用X.PagedList.Mvc.Core分页 & 搜索
Asp.Net Core 使用X.PagedList.Mvc.Core分页 & 搜索
127 0
|
6月前
|
开发框架 前端开发 JavaScript
JavaScript云LIS系统源码ASP.NET CORE 3.1 MVC + SQLserver + Redis医院实验室信息系统源码 医院云LIS系统源码
实验室信息系统(Laboratory Information System,缩写LIS)是一类用来处理实验室过程信息的软件,云LIS系统围绕临床,云LIS系统将与云HIS系统建立起高度的业务整合,以体现“以病人为中心”的设计理念,优化就诊流程,方便患者就医。
81 0
|
6月前
|
开发框架 前端开发 .NET
进入ASP .net mvc的世界
进入ASP .net mvc的世界
|
6月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
192 0
|
6月前
|
开发框架 前端开发 .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,然后在重定向到另
344 5
|
存储 开发框架 前端开发
[回馈]ASP.NET Core MVC开发实战之商城系统(五)
经过一段时间的准备,新的一期【ASP.NET Core MVC开发实战之商城系统】已经开始,在之前的文章中,讲解了商城系统的整体功能设计,页面布局设计,环境搭建,系统配置,及首页【商品类型,banner条,友情链接,降价促销,新品爆款】,商品列表页面,商品详情等功能的开发,今天继续讲解购物车功能开发,仅供学习分享使用,如有不足之处,还请指正。
167 0

热门文章

最新文章

下一篇
无影云桌面