分享好友 编程语言首页 频道列表

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

ASP.NET  2023-02-09 01:430

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

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

查看更多关于【ASP.NET】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
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

0评论2023-02-09888

Asp.Net Core 自定义验证属性
  很多时候,在模型上的验证需要自己定义一些特定于我们需求的验证属性。所以这一篇我们就来介绍一下怎么自定义验证属性。  我们来实现一个验证邮箱域名的自定义验证属性,当然,最重要的是需要定义一个继承自ValidationAttribute的类,然后在实现其IsVal

0评论2023-02-09525

Asp.Net 之 枚举类型的下拉列表绑定
有这样一个学科枚举类型:/// 学科 /// /summary public enum Subject {None = 0,[Description("语文")]Chinese = 1,[Description("数学")]Mathematics = 2,[Description("英语")]English = 3,[Description("政治")]Politics = 4,[Description("物理&qu

0评论2023-02-09819

[ASP.NET笔记] 1.Web基础知识
     1:http协议:     2:web服务器:     3:静态网页的概念     4:动态网页的概念       http协议:http(hypertext transfer protocol) 即超文本传输协议,这个协议是在internet上进行信息传送的协议任何网页之间要相互沟通,必须要尊循

0评论2023-02-09663

ASP.NET邮件发送 .net 发送邮件
  今天做了个ASP.NET做发送邮件功能,发现QQ邮箱好奇怪,当你用QQ邮箱做服务器的时候什么邮件都发送不出去(QQ邮箱除外)。而且爆出这样的错误:"邮箱不可用。 服务器响应为: Error: content rejected.http://mail.qq.com/zh_CN/help/content/rejectedmail.ht

0评论2023-02-09455

由ASP.NET Core根据路径下载文件异常引发的探究
前言    最近在开发新的项目,使用的是ASP.NET Core6.0版本的框架。由于项目中存在文件下载功能,没有使用类似MinIO或OSS之类的分布式文件系统,而是下载本地文件,也就是根据本地文件路径进行下载。这其中遇到了一个问题,是关于如何提供文件路径的,通

0评论2023-02-09562

ASP.NET 后台接收前台POST过来的json数据方法
 ASP.NET前后台交互之JSON数据 https://www.cnblogs.com/ensleep/p/3319756.html

0评论2023-02-09501

Asp.Net 常用工具类之加密——对称加密DES算法(2)
     又到周末,下午博客园看了两篇文章,关于老跳和老赵的程序员生涯,不禁感叹漫漫程序路,何去何从兮!  转眼毕业的第三个年头,去过苏州,跑过上海,从一开始的凌云壮志,去年背起行囊默默回到了长沙准备买房,也想有个家(毕竟年级不小了),有盼

0评论2023-02-09995

把自己的ASP.NET应用程序与SharePoint集成在一起
微软有文档描述这个解决方法的, 如下.   How to enable an ASP.Net application to run on a SharePoint virtual server http://support.microsoft.com/kb/828810?&clcid=0x409 Allowing Web Applications to Coexist with Windows SharePoint Services http

0评论2023-02-09749

ASP.NET中的OutOfMemoryException
在博客园看到了一位园友写的文章《如何处理OutOfMemoryException异常?》,于是想和大家交流一下ASP.NET中出现OutOfMemoryException的问题。实际上,在ASP.NET Web服务器上,ASP.NET所能够用到的内存,通常不会等同于所有的内存数量。在machine.config配置文

0评论2023-02-09823

【Mono】Linux下的Asp.Net配置指南
本文将介绍如何在Linux操作系统上搭建Asp.Net服务,在阅读本文之前,读者要先确 定自己已经安装好Linux操作系统、Mono Runtime,假如需要使用mod_mono的话,还 需要首先完成Apache的安装和配制。Mono的安装和配置请参考这里。 XSP XSP是一个轻量级的Web服务器

0评论2023-02-09312

EXT调用ASP.NET AJAX WebService
Posted 周五, 04/11/2008 - 16:34 by admin 在asp.net ajax中,使客户端调用WebService变得非常的简单,而且非常有用(个人觉得这个功能是asp.net ajax的核心,很多与客户端的交互都需要这个功能来辅助实现)。那在EXT中,标准的客户端与服务器端交互,使用的

0评论2023-02-09499

asp.net中Timer定时器在web中无刷新的使用
最近在做一个项目的时候,web端的数据需要与数据源进行实时同步,并保证数据的准确性,当时,考虑到使用ajax异步刷新技术。但后来在网上查找相关资料时,发现这样做,太浪费资源了,因为ajax的提交请求不应该这么频繁的,只适用于那种手动请求响应的那种,因

0评论2023-02-09961

ASP.Net访问母版页(MasterPage)控件、属性、方法及母版页中调用内容页的方法
总结了一下ASP.Net访问母版页控件、属性、方法及母版页中调用内容页的方法,供大家参考: 首先,必须通过内容页中的MasterTye指令,对母版页实施强类型化,即在内容页代码头的设置中增加如下指令%@ MasterType VirtualPath="~/Master/MenuElement.master" %

0评论2023-02-09783

asp.net 2.0 ajax中使用PopupControlExtender
 最近在著名的4guysfromrolla.com(http://www.4guysfromrolla.com)上,有篇不错的文章(http://aspnet.4guysfromrolla.com/articles/070407-1.aspx),讲的是如何使用aspajx中的controltookit中的PopupControlExtender控件来实现一些特殊的效果,比如文中举了

0评论2023-02-09965

更多推荐