ASP.NET MVC 2扩展点之Model Binder实例分析

   2023-02-09 学习力0
核心提示:MVC 2的Model可以是任意一个类。许多教程只讲“ADO.NET实体数据模型”Model1.edmx然后连接mssql2005以上,自动生成数据模型。这样会让初学者不能更好地理解Model与View之间的关系。这里我详细介绍一下怎样用任意一个类做Model,这样你也可以在MVC项目中使用Ac

MVC 2的Model可以是任意一个类。
许多教程只讲“ADO.NET实体数据模型”Model1.edmx
然后连接mssql2005以上,自动生成数据模型。
这样会让初学者不能更好地理解Model与View之间的关系。
这里我详细介绍一下怎样用任意一个类做Model,
这样你也可以在MVC项目中使用Access数据库,任意数据库吧。

步骤:新建MVC项目
删除默认生成的Controller,View,我喜欢简洁,突出重点。
右击Models目录,新建Book.cs

大气象
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcModelBinder.Models
{
    
public class Book
    {
        
public string Title { getset; }
        
public string Author { getset; }
        
public DateTime DatePublished { getset; }
    }
}

 

同上,新建BookModelBinder.cs,这样你就可以像“ADO.NET实体数据模型”使用任意类做Model了。

大气象
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Web.Mvc;//IModelBinder命名空间

namespace MvcModelBinder.Models
{
    
public class BookModelBinder : IModelBinder
    {

        
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var book 
= (Book)(bindingContext.Model ?? new Book());
            book.Title 
= GetValue<string>(bindingContext, "Title");
            book.Author 
= GetValue<string>(bindingContext, "Author");
            book.DatePublished 
= GetValue<DateTime>(bindingContext, "DatePublished");
            
if (String.IsNullOrEmpty(book.Title))
            {
                bindingContext.ModelState.AddModelError(
"Title""书名不能为空?");
            }

            
return book;
        }


        
private T GetValue<T>(ModelBindingContext bindingContext, string key)
        {
            ValueProviderResult valueResult 
= bindingContext.ValueProvider.GetValue(key);
            bindingContext.ModelState.SetModelValue(key, valueResult);
            
return (T)valueResult.ConvertTo(typeof(T));
        }
    }
}

 

新建BookController.cs这里提交添加表单的时候,把数据保存在TempData中。

大气象
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using MvcModelBinder.Models;

namespace MvcModelBinder.Controllers
{
    
public class BookController : Controller
    {
        
#region 添加的代码

        
public ActionResult List()
        {
            List
<Book> bookList = new List<Book>();

            Book book 
= new Book();
            book.Title 
= "书名";
            book.Author 
= "作者";
            book.DatePublished 
= DateTime.Now;
            bookList.Add(book);

            
if (TempData["NewBook"!= null)
            {
                Book newBook 
= TempData["NewBook"as Book;
                bookList.Add(newBook);
            }

            
return View(bookList);
        }

        
//
        
// GET: /Book/Create

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

        
//
        
// POST: /Book/Create

        [HttpPost]
        
public ActionResult Create(Book book)
        {
            
try
            {
                
// TODO: Add insert logic here
                Book newBook = new Book();
                newBook.Author 
= book.Author;
                newBook.Title 
= book.Title;
                newBook.DatePublished 
= book.DatePublished;
                TempData[
"NewBook"= book;

                
return RedirectToAction("List");
            }
            
catch
            {
                
return View();
            }
        }

        
#endregion

        
//
        
// GET: /Book/

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

        
//
        
// GET: /Book/Details/5

        
public ActionResult Details(int id)
        {
            
return View();
        }
        
        
//
        
// GET: /Book/Edit/5
 
        
public ActionResult Edit(int id)
        {
            
return View();
        }

        
//
        
// POST: /Book/Edit/5

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

        
//
        
// GET: /Book/Delete/5
 
        
public ActionResult Delete(int id)
        {
            
return View();
        }

        
//
        
// POST: /Book/Delete/5

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

 

新建View:List.aspx,Create.aspx这里创建强类型视图,可以选择Book
Create.aspx

大气象
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcModelBinder.Models.Book>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>Create</title>
</head>
<body>
    
<% using (Html.BeginForm()) {%>
        
<%: Html.ValidationSummary(true%>

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

    
<% } %>

    
<div>
        
<%: Html.ActionLink("Back to List""Index"%>
    
</div>

</body>
</html>

 

List.aspx

大气象
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcModelBinder.Models.Book>>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>List</title>
</head>
<body>
    
<table>
        
<tr>
            
<th></th>
            
<th>
                Title
            
</th>
            
<th>
                Author
            
</th>
            
<th>
                DatePublished
            
</th>
        
</tr>

    
<% foreach (var item in Model) { %>
    
        
<tr>
            
<td>
                
<%: Html.ActionLink("Edit""Edit"new { /* id=item.PrimaryKey */ }) %> |
                
<%: Html.ActionLink("Details""Details"new { /* id=item.PrimaryKey */ })%> |
                
<%: Html.ActionLink("Delete""Delete"new { /* id=item.PrimaryKey */ })%>
            
</td>
            
<td>
                
<%: item.Title %>
            
</td>
            
<td>
                
<%: item.Author %>
            
</td>
            
<td>
                
<%String.Format("{0:g}", item.DatePublished) %>
            
</td>
        
</tr>
    
    
<% } %>

    
</table>

    
<p>
        
<%: Html.ActionLink("Create New""Create"%>
    
</p>

</body>
</html>

 

最后据说需要在Global.asax中注册,我没有注册一样不出错。可能哪里理解不到位。

大气象
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

using MvcModelBinder.Models;

namespace MvcModelBinder
{
    
// 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,
    
// 请访问 http://go.microsoft.com/?LinkId=9394801

    
public class MvcApplication : System.Web.HttpApplication
    {
        
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute(
"{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                
"Default"// 路由名称
                "{controller}/{action}/{id}"// 带有参数的 URL
                new { controller = "Book", action = "List", id = UrlParameter.Optional } // 参数默认值
            );

        }

        
protected void Application_Start()
        {
            
//据说需要这样注册一下,我不注册也不影响。不知道哪里理解不到位。
            ModelBinders.Binders.Add(typeof(Book), new BookModelBinder());

            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
        }
    }
}

 

这是最终的目录结构:

ASP.NET MVC 2扩展点之Model Binder实例分析

本文源码:https://files.cnblogs.com/greatverve/MvcModelBinder.rar

参考:http://www.cnblogs.com/zhuqil/archive/2010/07/31/you-have-to-knowextensibility-points-in-asp-net-mvc-model-binder.html

这里这个大牛,不屑过多解释,这个工作由我来做吧。

 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • 使用WebClient自动填写并提交ASP.NET页面表单的源代码
    使用WebClient自动填写并提交ASP.NET页面表单的
    转自:http://www.cnblogs.com/anjou/archive/2007/03/07/667253.html 在.NET中通过程序填写和提交表单还是比较简单。比如,要提交一个如下图所示的登录表单:           填写和提交以上表单的代码如下:       // 要提交表单的URI字符串
    02-09
  • asp.net mvc多条件+分页查询解决方案
    


            
asp.net mvc多条件+分页查询解决方案
    asp.net mvc多条件+分页查询解决方案
    http://www.cnblogs.com/nickppa/p/3232535.html开发环境vs2010css:bootstrapjs:jquery    bootstrap paginator原先只是想做个mvc的分页,但是一般的数据展现都需要检索条件,而且是多个条件,所以就变成了MVC多条件+分页查询因为美工不是很好,所以用的是
    02-09
  • ASP.NET操作Cookies的问题(Bug or Not)
    以下存和取都是在不同的页面中,如果是在同一个页面也没必要用cookies了。 Test1: 给Cookies赋值: const string AAA="aaa"; Response.Cookies[AAA].Value = "111;222;333"; 取值: string value = Request.Cookies[AAA].Value; // value为111 Test2: 给Cooki
    02-09
  • Asp.Net Core 自定义验证属性
      很多时候,在模型上的验证需要自己定义一些特定于我们需求的验证属性。所以这一篇我们就来介绍一下怎么自定义验证属性。  我们来实现一个验证邮箱域名的自定义验证属性,当然,最重要的是需要定义一个继承自ValidationAttribute的类,然后在实现其IsVal
    02-09
  • Asp.Net 之 枚举类型的下拉列表绑定
    有这样一个学科枚举类型:/// 学科 /// /summary public enum Subject {None = 0,[Description("语文")]Chinese = 1,[Description("数学")]Mathematics = 2,[Description("英语")]English = 3,[Description("政治")]Politics = 4,[Description("物理&qu
    02-09
  • [ASP.NET笔记] 1.Web基础知识
         1:http协议:     2:web服务器:     3:静态网页的概念     4:动态网页的概念       http协议:http(hypertext transfer protocol) 即超文本传输协议,这个协议是在internet上进行信息传送的协议任何网页之间要相互沟通,必须要尊循
    02-09
  • ASP.NET邮件发送 .net 发送邮件
      今天做了个ASP.NET做发送邮件功能,发现QQ邮箱好奇怪,当你用QQ邮箱做服务器的时候什么邮件都发送不出去(QQ邮箱除外)。而且爆出这样的错误:"邮箱不可用。 服务器响应为: Error: content rejected.http://mail.qq.com/zh_CN/help/content/rejectedmail.ht
    02-09
  • 由ASP.NET Core根据路径下载文件异常引发的探究
    前言    最近在开发新的项目,使用的是ASP.NET Core6.0版本的框架。由于项目中存在文件下载功能,没有使用类似MinIO或OSS之类的分布式文件系统,而是下载本地文件,也就是根据本地文件路径进行下载。这其中遇到了一个问题,是关于如何提供文件路径的,通
    02-09
  • ASP.NET的运行原理与运行机制 ASP.NET的开发模式包括
    ASP.NET的运行原理与运行机制 ASP.NET的开发模
    在Asp.net4和4.5中,新增了WebPages Framework,编写页面代码使用了新的Razor语法,代码更加的简洁和符合Web标准,编写方式更接近于PHP和以前的Asp,和使用WebForms这种模仿Windows Form编程方式有了很大不同,不再有大量控件和控件生成的大量不够灵活的代码
    02-09
  • ASP.NET 后台接收前台POST过来的json数据方法
     ASP.NET前后台交互之JSON数据 https://www.cnblogs.com/ensleep/p/3319756.html
    02-09
点击排行