ASP.NET MVC 2入门演练 3 - 列表和添加功能

一、列表显示-View:List.aspx

  此功能实现起来比较简单,之前我们在Site.Master添加了如下一行代码:

<li><%: Html.ActionLink("News""List""News")%></li>

 

  其中"List"就是指定Action,最后面的"News“指定的是Controller,所以,只需要在NewsController中实现List方法即可。以下代码是NewsController类中的List方法。

//读取CMSNews表中的所有数据行并按ID降序排列
public ActionResult List()
{
    
return View(db.CMSNews.OrderByDescending(Model => Model.ID).ToList());
}

 

  db是在类NewsController中声明的成员:

MVCDemoEntities db = new MVCDemoEntities();

 

  MVCDemoEntities哪里来的呢,查看以下Web.config中的链接字符串:

 

<add name="MVCDemoEntities" connectionString="metadata=res://*/Models.MVCDemoModel.csdl|res://*/Models.MVCDemoModel.ssdl|res://*/Models.MVCDemoModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\MSSQLSERVER2008;Initial Catalog=MVCDemo;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

 

    

   到此列表显示功能完成,我这里没有更改View中的代码,您可以根据需要去更改,比如把表格改成div,删除一些不想再列表中显示的列等。

     另外,自动生成的代码我都没改,实际上,像<%: Html.ActionLink("Edit", "Edit", new { id=item.ID }) %>ActionLink中的参数可以自定义的。

 二、实现添加功能 - View:Create.aspx

  1)View中我把自动生成的验证代码去掉,使用了JQuery的表单验证功能,另外<form>也去掉自动生成的代码而改为下面的代码:

//执行NewsController中的Create方法
<form id="frmCreate" action="<%=Url.Action("Create","News")%>" method="post">

  代码如下:

     <!--添加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>

 

  NewsController中Create方法实现代码:

//
        
// 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();
            }
        }

   运行后界面,输入错误时:

  

  输入正确时:

  

  表单中的HTML代码:

<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) %>
        
</div>
        
<p>
            
<input type="submit" value="Create" />
        
</p>
    
</fieldset>

 

   CMSNewsCategory是新闻分类表只有两列:编码和名称,编码是主键,只需要Update一下Model,选中此表即可:

  双击MVCDemoModel.edmx,在Model Browser中右击EntityContainer:MVCDemoEntities,右键菜单选择【Update Model From Database】,在出现的窗口中展开表并选中CMSNewsCategory,然后【Finish】。

   下一篇中,实现浏览、修改和删除功能。

posted on 2010-05-30 20:38  Ferry  阅读(2881)  评论(2编辑  收藏  举报

导航