在ASP.NET MVC中对表进行通用的增删改
http://www.cnblogs.com/nuaalfm/archive/2009/11/11/1600811.html
预备知识:
1、了解反射技术
2、了解C#3.0中扩展方法,分布类,Linq to object,Linq to sql
3、了解ASP.NET MVC
在项目中每添加一个表往往都要添加一套增删改代码,而且这些代码很多情况下都很相似,这里我们给出一个通用的解决方案供大家参考。
一、准备工作:
这里我们先要在数据库中添加两个表News和User如下图:然后拖到dbml中生成实体类。
这里我们先准备一个接口:ICommonTable
Code
public interface ICommonTable
{
int id { get; set; }
}
然后让News和User实体都继承于此接口
Code
public partial class News : ICommonTable
{ }
public partial class User : ICommonTable
{
}
二、通用删除操作
分别添加NewsList.aspx和UserList.aspx两个view,添加方式参见ASP.NET MVC实践系列2-简单应用
在这两个View中加入删除链接:
<%= Html.ActionLink("删除", "Delete", new { key = item.id, partialName="News" })%>
和
<%= Html.ActionLink("删除", "Delete", new { key = item.id, partialName="User" })%>
然后添加一个Controller:
public ActionResult Delete(string partialName, int? key)
{
RepositoryBase repositoryBase = new RepositoryBase(partialName);
repositoryBase.Delete(key ?? 0);
return RedirectToAction(partialName + "List");//返回到list
}
public class RepositoryBase
{
public Type EntityType { get; private set; }
public RepositoryBase(string entityType)
{
Type type = GetBllTypeByName(entityType); EntityType = type;
}
public ICommonTable CreateNew()
{
return (ICommonTable)Activator.CreateInstance(EntityType);
}
/// <summary>
/// 通过字符串获得其Type
/// </summary>
/// <param name="typeName"></param>
/// <returns></returns>
private static Type GetBllTypeByName(string typeName)
{
Type type = null;
var ass = AppDomain.CurrentDomain.GetAssemblies()
.Where(p => p.FullName.Contains("CommonCEDemo"));
foreach (var a in ass)
{
type = a.GetTypes().Where(p => p.Name == typeName).FirstOrDefault();
if (type != null)
break;
} if (type == null)
{
throw new Exception("类型未定义:" + typeName);
}
return type;
}
public RepositoryBase(Type entityType)
{
EntityType = entityType;
}
public ICommonTable Get(int id)
{
DBDataContext db = Context.GetContext();
return db.GetTable(EntityType).Cast<ICommonTable>().FirstOrDefault(p => p.id == id);
}
public void Delete(int id)
{
ICommonTable bllTable = Get(id);
Context.GetContext().GetTable(EntityType).DeleteOnSubmit(bllTable);
Context.GetContext().SubmitChanges();
}
}
public class Context
{
static DBDataContext context;
static Context()
{
if (context==null)
{
context = new DBDataContext();
}
}
public static DBDataContext GetContext()
{
return context;
}
}
有个这些当我们想要对一个表进行删除是只要添加相应的链接就可以了(如<%= Html.ActionLink("删除", "Delete", new { key = item.id, partialName="News" })%>)
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <%Html.RenderPartial(ViewData["PartialName"].ToString()); %> </asp:Content>
public ActionResult CreateEditView(string partialName, int? key)
{ ViewData["PartialName"] = partialName; RepositoryBase repositoryBase = new RepositoryBase(partialName);
ICommonTable table;
if (key == null)
{
table = repositoryBase.CreateNew();
}
else
{
table = repositoryBase.Get(key ?? 0);
} return View("CreateEditView", table);
} [AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateEditView(string partialName, int? key, FormCollection formCollection)
{
RepositoryBase repositoryBase = new RepositoryBase(partialName);
ICommonTable bllTable;
if (key == null)
{
bllTable = repositoryBase.CreateNew();
}
else
{
bllTable = repositoryBase.Get(key ?? 0);
} this.UpdateModel(bllTable, true);
if (key == null)
{
Context.GetContext().GetTable(repositoryBase.EntityType).InsertOnSubmit(bllTable); } Context.GetContext().SubmitChanges(); return RedirectToAction(partialName+"List");//返回到list
}
protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IDictionary<string, ValueProviderResult> valueProvider) where TModel : class {
if (model == null) {
throw new ArgumentNullException("model");
}
if (valueProvider == null) {
throw new ArgumentNullException("valueProvider");
} Predicate<string> propertyFilter = propertyName => BindAttribute.IsPropertyAllowed(propertyName, includeProperties, excludeProperties);
IModelBinder binder = Binders.GetBinder(typeof(TModel)); ModelBindingContext bindingContext = new ModelBindingContext() {
Model = model,
ModelName = prefix,
ModelState = ModelState,
ModelType = typeof(TModel),
PropertyFilter = propertyFilter,
ValueProvider = valueProvider
};
binder.BindModel(ControllerContext, bindingContext);
return ModelState.IsValid;
}
这个typeof(TModel)造成了只会更新声明类型中有的属性,把它换成model.GetType()就可以解决问题了,我扩这的这个方法如下
public static class ControllerExtension
{
/// <summary>
/// 更新时是否按照当前类型进行更新
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <param name="controller"></param>
/// <param name="model"></param>
/// <param name="isEx"></param>
public static void UpdateModel<TModel>(this Controller controller, TModel model, bool isExtension) where TModel : class
{
if (isExtension)
{
Predicate<string> propertyFilter = propertyName => IsPropertyAllowed(propertyName, null, null);
IModelBinder binder = ModelBinders.Binders.GetBinder(model.GetType()); ModelBindingContext bindingContext = new ModelBindingContext()
{
Model = model,
ModelName = null,
ModelState = controller.ModelState,
ModelType = model.GetType(),
PropertyFilter = propertyFilter,
ValueProvider = controller.ValueProvider
};
binder.BindModel(controller.ControllerContext, bindingContext); }
else
{
throw new Exception("isExtension不能选择false");
}
}
private static bool IsPropertyAllowed(string propertyName, string[] includeProperties, string[] excludeProperties)
{
bool includeProperty = (includeProperties == null) || (includeProperties.Length == 0) || includeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase);
bool excludeProperty = (excludeProperties != null) && excludeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase);
return includeProperty && !excludeProperty;
}
}
有了这些,当我们想对新表进行编辑和添加时只需要添加相应的Partial编辑视图就可以了,简化了我们的编程工作。
在ASP.NET MVC中对表进行通用的增删改的更多相关文章
- 【转载】ASP.NET MVC Web API 学习笔记---联系人增删改查
本章节简单介绍一下使用ASP.NET MVC Web API 做增删改查.目前很多Http服务还是通过REST或者类似RESP的模型来进行数据操作的.下面我们通过创建一个简单的Web API来管理联系 ...
- ASP.NET MVC Web API 学习笔记---联系人增删改查
本章节简单介绍一下使用ASP.NET MVC Web API 做增删改查. 目前很多Http服务还是通过REST或者类似RESP的模型来进行数据操作的. 下面我们通过创建一个简单的Web API来管理 ...
- 3、ASP.NET MVC入门到精通——Entity Framework增删改查
这里我接上讲Entity Framework入门.从网上下载Northwind数据库,新建一个控制台程序,然后重新添加一个ado.net实体数据模型. EF中操作数据库的"网关"( ...
- asp.net mvc 三层加EF 登录注册 增删改查
首先打开vs软件新建项目创建web中的mvc项目再右击解决方案创建类库项目分别创建DAL层和BLL层再把DAL层和BLL层的类重命名在mvc项目中的Models文件夹创建model类在DAL创建ADO ...
- Asp.net mvc中的Ajax处理
在Asp.net MVC中的使用Ajax, 可以使用通用的Jquery提供的ajax方法,也可以使用MVC中的AjaxHelper. 这篇文章不对具体如何使用做详细说明,只对于在使用Ajax中的一些需 ...
- ASP.NET MVC 中使用 AjaxFileUpload 插件时,上传图片后不能显示(预览)
AjaxFileUpload 插件是一个很简洁很好用的上传文件的插件,可以实现异步上传功能,但是在 ASP.NET MVC中使用时,会出现上传图片后不能正确的显示的问题,经过仔细排查,终于找到原因,解 ...
- 在ASP.NET MVC 中获取当前URL、controller、action 、参数
URL的获取很简单,ASP.NET通用:[1]获取 完整url (协议名+域名+虚拟目录名+文件名+参数) string url=Request.Url.ToString(); [2]获取 虚拟目录名 ...
- ASP.NET MVC中注册Global.asax的Application_Error事件处理全局异常
在ASP.NET MVC中,通过应用程序生命周期中的Application_Error事件可以捕获到网站引发的所有未处理异常.本文作为学习笔记,记录了使用Global.asax文件的Applicati ...
- 2.ASP.NET MVC 中使用Crystal Report水晶报表
上一篇,介绍了怎么导出Excel文件,这篇文章介绍在ASP.NET MVC中使用水晶报表. 项目源码下载:https://github.com/caofangsheng93/CrystalReport ...
随机推荐
- Cocos2dx源码赏析(3)之事件分发
Cocos2dx源码赏析(3)之事件分发 这篇,继续从源码的角度赏析下Cocos2dx引擎的另一模块事件分发处理机制.引擎的版本是3.14.同时,也是学习总结的过程,希望通过这种方式来加深对Cocos ...
- bc命令详解
基础命令学习目录首页 原文链接:https://www.cnblogs.com/lovevivi/p/4359296.html 最近经常要在linux下做一些进制转换,看到了可以使用bc命令,如下: ...
- 深入 JSX
从本质上讲,JSX 只是为 React.createElement(component, props, ...children) 函数提供的语法糖.JSX代码: 1 2 3 <MyButton ...
- Scrum立会报告+燃尽图(十二月八日总第三十九次):制定视频方案
此作业要求参见:https://edu.cnblogs.com/campus/nenu/2018fall/homework/2284 项目地址:https://git.coding.net/zhang ...
- Daily Scrum 11.7
明后两天周六日,按照TFS的日常安排应该是休息,所以让他们自由完成已经分配的任务. 姓名 今日任务 黄新越 提取爬取网页的关键字并输出到接口 刘垚鹏 程序总架构的修改与多线程的学习 王骜 多线程学习 ...
- 爱码室Crawler & classification module项目工作分配
项目情况 爬虫项目是上届学生遗留下来的项目,他们已经实现了基础的功能,而我们来负责完善,主要需要解决的问题是怎么让爬虫脱离爬和停的繁琐指令,更加的智能化.所以我们的计划是在前人的源码基础上,加以修改测 ...
- cocos2d-x 相关文章资源(安卓开发)
http://blog.csdn.net/sdhjob/article/details/38734993 http://www.cnblogs.com/code4app/p/4026665.html ...
- Oracle Form Builder
Oracle Form Builder 是Oracle的一个开发工具,可以针对Oracle公司的E-Business Suit的ERP系统开发的.对应的还有reports builder. Oracl ...
- 深入浅析JavaScript的API设计原则(转载)
一.接口的流畅性 好的接口是流畅易懂的,他主要体现如下几个方面: 1.简单 操作某个元素的css属性,下面是原生的方法: ? 1 document.querySelectorAll('#id').st ...
- grep文本处理工具
grep是一款文本过滤工具,基于正则表达式进行模式匹配sed:stream editor 流编辑器awk:linux上实现为gawk,文本报告生成器(格式化文本)文本搜索工具,根据用户指定的模式,对目 ...