http://msdn.microsoft.com/zh-cn/library/dd410405(v=vs.100).aspx

在ASP.NET MVC框架中,模型是负责核心应用程序或业务逻辑的应用程序部件。模型对象通常从诸如SQL Server之类的永久存储区中访问数据,并对该数据执行业务逻辑。模型特定于应用程序,因此ASP.NET MVC框架对您可以生成的模型对象的种类没有限制。例如,您可以使用ADO.NET DataSet或DataReader对象,或者可以使用一组自定义的域对象。您也可以使用对象类型的组合来处理数据。

 

模型不是特定的类或接口。类是模型的一部分,这并不是因为它可以实现某接口或派生自某基类。而是由于类在ASP.NET MVC应用程序中发挥的作用,以及类在应用程序文件夹结构中的存储位置的缘故。ASP.NET MVC应用程序中的模型类不直接处理来自浏览器的输入也不生成到浏览器的HTML输出

 

定义模型

模型对象是实现域逻辑(也称为业务逻辑)的应用程序部件。域逻辑可处理在数据库与UI之间传递的数据。例如,在库存系统中,模型将跟踪存储区中的物品以及用于确定库存中是否有某个物品的逻辑。此外,模型将是物品卖出并从仓库中发货时对数据库进行更新的应用程序部件。通常,模型还将在数据库中的存储和检索模型状态。

 

集成模型和控制器

建议用于存储模型类的文件夹为ASP.NET MVC应用程序模板中Visual Studio提供的Models文件夹。但是,通常也会将模型类存放在单独的程序集中,以便您可以在不同的应用程序中重复使用这些类。

若要使用控制器中的模型类,通常应执行以下步骤:实例化控制器操作中的模型类、调用模型对象的方法以及从这些对象中提取相应数据以在视图中显示。这是推荐用于实现操作的方法。此方法还可以使应用程序的逻辑元素保持分离,这样就可以轻松地测试应用程序逻辑,而不必通过用户界面测试该逻辑。

下面的示例演示一个代表人员的简单模型类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcSimpleModelBinding.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public int Zipcode { get; set; }
    }
}

 

模型联编程序

MVC 中的模型联编程序提供了一种简单的方法,用于将已发送的窗体值映射到 .NET Framework 类型并将该类型以参数形式传递给操作方法。<?XML:NAMESPACE PREFIX = [default] http://www.w3.org/1999/xhtml NS = "http://www.w3.org/1999/xhtml" />通过使用联编程序,您还可以控制传递给操作方法的类型的反序列化。模型联编程序类似于类型转换器,因为它们可以将 HTTP 请求转换成传递给操作方法的对象。但是,它们还包含有关当前控制器上下文的信息。

通过使用模型联编程序,您可以与使用操作方法参数或类型来实现 IModelBinder 接口的类相关联。 IModelBinder 接口包含 GetValue 方法,框架将会调用此方法以便检索指定参数或类型的值。 DefaultModelBinder 类适用于大多数 .NET Framework 类型,包括数组和 IListICollection,以及 IDictionary 对象。

 

模型绑定示例

下面的示例演示如何实现简单的模型绑定。本示例中使用的模型是在上一个示例中定义的 Person 类。本示例包括 PersonController 类,以及 Index 视图、Create 视图和 Details 视图。 PersonController 类将创建一个用于存储 Person 对象的列表。 Index 视图显示列表中每个 Person 对象的 Id 和 Name 属性。通过使用 Create视图,用户可以输入人员信息。 Details 视图显示选定人员的所有信息。

下面的示例演示 PersonController 类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class PersonController : Controller
    {
        static List<Person> people = new List<Person>();

        //
        // GET: /Person/
        public ActionResult Index()
        {
            return View(people);
        }

        //
        // GET: /Person/Details/5
        public ActionResult Details(int id)
        {
            return View(people.Single(c => c.Id.Equals(id)));
        }

        //
        // GET: /Person/Create
        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Person/Create
        //[HttpPost]
        //public ActionResult Create(FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add insert logic here

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}

        //[AcceptVerbs(HttpVerbs.Post)]
        [HttpPost]
        public ActionResult Create(Person person)
        {
            if (!ModelState.IsValid)
            {
                return View("Create", person);
            }

            people.Add(person);
            return RedirectToAction("Index");
        }
        
        //
        // GET: /Person/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View(people.Single(c => c.Id.Equals(id)));
        }

        //
        // POST: /Person/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                Person p = people.Single(c => c.Id.Equals(id));
                p.Name = collection["Name"];
                p.Age = Int32.Parse(collection["Age"]);
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Person/Delete/5
 
        public ActionResult Delete(int id)
        {
            Person p = people.SingleOrDefault(c => c.Id == id);
            if (p != null)
            {
                people.Remove(p);
            }

            return RedirectToAction("Index");
            //return View();
        }

        //
        // POST: /Person/Delete/5

        //[HttpPost]
        //public ActionResult Delete(int id, FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add delete logic here
 
        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}
    }
}

 

下面的示例演示 Index 视图:

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

<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>Name</th>
            <th>Age</th>
        </tr>

    <% foreach (var person in Model) { %>
        <tr>
            <td>
                <%= Html.ActionLink("Edit", "Edit", new { id=person.Id }) %> |
                <%= Html.ActionLink("Details", "Details", new { id=person.Id})%> |
                <%= Html.ActionLink("Delete", "Delete", new { id=person.Id })%>
            </td>
            <td>
                <%= Html.Encode(person.Id)%>
            </td>
            <td>
                <%= Html.Encode(person.Name)%>
            </td>
            <td>
                <%= Html.Encode(person.Age)%>
            </td>
        </tr>
    
    <% } %>

    </table>

    <p>
        <%= Html.ActionLink("Create New", "Create") %>
    </p>

</asp:Content>

 

下面的示例演示 Create 视图:

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

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Create
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Create</h2>

    <% using (Html.BeginForm()) {%>
        <%= Html.ValidationSummary(true) %>

        <fieldset>
            <legend>Fields</legend>
            
            <div class="editor-label">
                <%= Html.LabelFor(model => model.Id) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(model => model.Id) %>
                <%= Html.ValidationMessageFor(model => model.Id) %>
            </div>
            
            <div class="editor-label">
                <%= Html.LabelFor(model => model.Name) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(model => model.Name) %>
                <%= Html.ValidationMessageFor(model => model.Name) %>
            </div>
            
            <div class="editor-label">
                <%= Html.LabelFor(model => model.Age) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(model => model.Age) %>
                <%= Html.ValidationMessageFor(model => model.Age) %>
            </div>
            
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>

    <% } %>

    <div>
        <%= Html.ActionLink("Back to List", "Index") %>
    </div>

</asp:Content>

 

下面的示例演示 Detail 视图:

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

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Details
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Details</h2>

    <fieldset>
        <legend>Fields</legend>
        
        <div class="display-label">Id</div>
        <div class="display-field"><%= Html.Encode(Model.Id) %></div>
        
        <div class="display-label">Name</div>
        <div class="display-field"><%= Html.Encode(Model.Name) %></div>
        
        <div class="display-label">Age</div>
        <div class="display-field"><%= Html.Encode(Model.Age) %></div>
        
        <div class="display-label">Street</div>
        <div class="display-field"><%= Html.Encode(Model.Street) %></div>
        
        <div class="display-label">City</div>
        <div class="display-field"><%= Html.Encode(Model.City) %></div>
        
        <div class="display-label">State</div>
        <div class="display-field"><%= Html.Encode(Model.State) %></div>
        
        <div class="display-label">Zipcode</div>
        <div class="display-field"><%= Html.Encode(Model.Zipcode) %></div>
        
    </fieldset>
    <p>
        <%= Html.ActionLink("Edit", "Edit", new { id=Model.Id })%> |
        <%= Html.ActionLink("Back to List", "Index") %>
    </p>

</asp:Content>

 

下面的示例演示 Edit 视图:

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

<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>
            
            <%= Html.HiddenFor(m=>m.Id) %>

            <div class="editor-label">
                <%= Html.LabelFor(model => model.Name) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(model => model.Name) %>
                <%= Html.ValidationMessageFor(model => model.Name) %>
            </div>
            
            <div class="editor-label">
                <%= Html.LabelFor(model => model.Age) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(model => model.Age) %>
                <%= Html.ValidationMessageFor(model => model.Age) %>
            </div>
           
            <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>

    <% } %>

    <div>
        <%= Html.ActionLink("Back to List", "Index") %>
    </div>

</asp:Content>

 

效果截图:

image

image

image

image

image

posted on 2013-03-21 16:13  Louis.Lu.Sz  阅读(364)  评论(0编辑  收藏  举报