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   Ferry  阅读(3310)  评论(4编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
< 2010年5月 >
25 26 27 28 29 30 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示