ASP.NET MVC 2入门演练 4 - 浏览详细、修改和删除

一、浏览详细

   生成Details.aspx后,View不需要做任何修改(当然可以根据需要去调整View),直接在Controller中的Details方法中添加以下代码:

ViewData.Model = db.CMSNews.First(m => m.ID == id);
return View();

二、修改

   Edit.aspx根据Create.aspx修改了一下,加上验证:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MVC2Demo.Models.CMSNews>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Edit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    
<!--添加JQuery脚本引用-->
    
<script src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    
<script src="http://www.cnblogs.com/Scripts/jquery.validate.min.js" type="text/javascript"></script>
    
<!--JQuery表单验证脚本-->
    
<script type="text/javascript">
        $(document).ready(
            
function () {
                $(
"#frmCreate").validate({
                    rules: {
                        NewsTitle: { required: 
true },
                        NewsCategory: { required: 
true },
                        NewsContent: { required: 
true },
                        PubDate: { required: 
true,
                            date: 
true
                        }
                    },
                    messages: {
                        NewsTitle: 
'此项不能为空',
                        NewsCategory: 
'此项不能为空',
                        NewsContent: 
'此项不能为空',
                        PubDate: {
                            required: 
'此项不能为空',
                            date: 
'日期格式错误'
                        }
                    },
                    success: 
function (label) {
                        label.addClass(
"valid").text("")
                    }
                    
//submitHandler: function () { alert("操作已完成!") }
                }
            )
            }
        )
    
</script>
    
<h2>
        Edit
</h2>
    
<form id="frmCreate" action="<%=Url.Action("Edit","News")%>" method="post">
    
<fieldset>
        
<legend>Fields</legend>
        
<div class="editor-label">
            
<%: Html.LabelFor(model => model.NewsTitle) %>
        
</div>
        
<div class="editor-field">
            
<%: Html.TextBoxFor(model => model.NewsTitle) %>
        
</div>
        
<div class="editor-label">
            
<%: Html.LabelFor(model => model.NewsCategory) %>
        
</div>
        
<div class="editor-field">
            
<%: Html.DropDownListFor(model => model.NewsCategory,
                                        
new SelectList(new MVC2Demo.Models.MVCDemoEntities().CMSNewsCategory.ToList(),
                        
"CategoryCode","CategoryName"),"-- Select Category --")%>
        
</div>
        
<div class="editor-label">
            
<%: Html.LabelFor(model => model.NewsContent) %>
        
</div>
        
<div class="editor-field">
            
<%: Html.TextAreaFor(model => model.NewsContent, new { Style = "width:200px;height:100px" })%>
        
</div>
        
<div class="editor-label">
            
<%: Html.LabelFor(model => model.PubDate) %>
        
</div>
        
<div class="editor-field">
            
<%: Html.TextBoxFor(model => model.PubDate, String.Format("{0:g}", Model.PubDate)) %>
        
</div>
        
<p>
            
<input type="submit" value="Save" />
        
</p>
    
</fieldset>
    
</form>
    
<div>
        
<%: Html.ActionLink("Back to List""List"%>
    
</div>
</asp:Content>

 

  在Controller中实现Edit方法:

 

//
        
// GET: /News/Edit/5
        
// 浏览时
        public ActionResult Edit(int id)
        {
            ViewData.Model 
= db.CMSNews.First(m => m.ID == id);
            
return View();
        }

        
//
        
// POST: /News/Edit/5
        
// 提交修改时
        [HttpPost]
        
public ActionResult Edit(int id, FormCollection collection)
        {
            
try
            {
                
// TODO: Add update logic here
                CMSNews news = db.CMSNews.First(m => m.ID == id);
                news.NewsTitle 
= collection["NewsTitle"];
                news.NewsCategory 
= collection["NewsCategory"];
                news.NewsContent 
= collection["NewsContent"];
                news.PubDate 
= DateTime.Parse(collection["PubDate"]);
                db.SaveChanges();
                
return RedirectToAction("List");
            }
            
catch
            {
                
return View();
            }
        }

 

三、删除

  Delete.aspx中做了一点修改加上了JavaScript删除确认,实际上MVC 2中已经实现了这个功能,方式不一样,当你点击列表页中某一条信息的“Delete”时会进入详细信息页(Delete.aspx),在这个页面再点击"Delete"才真正删除数据。

<input type="submit" id="btnDel" value="Delete" /> 

 

 

<script src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(
        
function () {
            $(
"#btnDel").click(
                
function () {
                    
return confirm("Are you sure you want to delete this?");
                }
            )
        }
    )
</script> 

 

  然后去实现Controller中的Delete方法:

//
        
// GET: /News/Delete/5
        
// 浏览时
        public ActionResult Delete(int id)
        {
            ViewData.Model 
= db.CMSNews.First(m => m.ID == id);
            
return View();
        }

        
//
        
// POST: /News/Delete/5
        
// 提交删除时
        [HttpPost]
        
public ActionResult Delete(int id, FormCollection collection)
        {
            
try
            {
                
// TODO: Add delete logic here
                db.DeleteObject(db.CMSNews.First(m => m.ID == id));
                db.SaveChanges();
                
return RedirectToAction("List");
            }
            
catch
            {
                
return View();
            }
        }

 

  这样,三个功能很简单的就实现了,NewsController.cs完整代码如下:

using System;
using System.Linq;
using System.Web.Mvc;
using MVC2Demo.Models;

namespace MVC2Demo.Controllers
{
    
public class NewsController : Controller
    {
        MVCDemoEntities db 
= new MVCDemoEntities();
        
        
//
        
// GET: /News/

        
public ActionResult Index()
        {
            
return View();
        }
        
public ActionResult List()
        {
            
return View(db.CMSNews.OrderByDescending(Model => Model.PubDate).ToList());
        }

        
//
        
// GET: /News/Details/5

        
public ActionResult Details(int id)
        {
            ViewData.Model 
= db.CMSNews.First(m => m.ID == id);
            
return View();
        }

        
//
        
// GET: /News/Create

        
public ActionResult Create()
        {
            
return View();
        } 

        
//
        
// POST: /News/Create

        [HttpPost]
        
public ActionResult Create(FormCollection collection)
        {
            
try
            {
                
// TODO: Add insert logic here
                CMSNews news = new CMSNews();
                news.NewsTitle 
= collection["NewsTitle"];
                news.NewsCategory 
= collection["NewsCategory"];
                news.NewsContent 
= collection["NewsContent"];
                news.PubDate 
= DateTime.Parse(collection["PubDate"]);
                db.AddToCMSNews(news);
                db.SaveChanges();
                
return RedirectToAction("List");
            }
            
catch
            {
                
return View();
            }
        }
        
        
//
        
// GET: /News/Edit/5
        
// 浏览时
        public ActionResult Edit(int id)
        {
            ViewData.Model 
= db.CMSNews.First(m => m.ID == id);
            
return View();
        }

        
//
        
// POST: /News/Edit/5
        
// 提交修改时
        [HttpPost]
        
public ActionResult Edit(int id, FormCollection collection)
        {
            
try
            {
                
// TODO: Add update logic here
                CMSNews news = db.CMSNews.First(m => m.ID == id);
                news.NewsTitle 
= collection["NewsTitle"];
                news.NewsCategory 
= collection["NewsCategory"];
                news.NewsContent 
= collection["NewsContent"];
                news.PubDate 
= DateTime.Parse(collection["PubDate"]);
                db.SaveChanges();
                
return RedirectToAction("List");
            }
            
catch
            {
                
return View();
            }
        }

        
//
        
// GET: /News/Delete/5
        
// 浏览时
        public ActionResult Delete(int id)
        {
            ViewData.Model 
= db.CMSNews.First(m => m.ID == id);
            
return View();
        }

        
//
        
// POST: /News/Delete/5
        
// 提交删除时
        [HttpPost]
        
public ActionResult Delete(int id, FormCollection collection)
        {
            
try
            {
                
// TODO: Add delete logic here
                db.DeleteObject(db.CMSNews.First(m => m.ID == id));
                db.SaveChanges();
                
return RedirectToAction("List");
            }
            
catch
            {
                
return View();
            }
        }
    }
}

      源码和数据库备份:/Files/Ferry/VS2010/MVC2Demo.rar

  下一篇,我想先整理些关于ASP.NET MVC的基础入门知识,之后,再在此功能的基础上做些改进,使其更加贴近实际应用,比如:使用新闻编辑器、批量删除等。

posted on 2010-05-31 22:37  Ferry  阅读(3306)  评论(4编辑  收藏  举报

导航