ASP.NET MVC VIEW AND TRANSACTION
2013-07-07 00:13 yezhi 阅读(287) 评论(0) 收藏 举报http://weblogs.asp.net/rashid/archive/2009/11/11/asp-net-mvc-view-and-transaction.aspx
ASP.NET MVC VIEW AND TRANSACTION
Scott showed how to render the Grid in a Transaction. Certainly it does the job but in my opinion view component should not be responsible for this kind of cross cutting concerns, instead we can use the Action Filters. Lets see how we can utilize the Action Filter in this scenario instead of modifying the Grid code. What Scott is trying to do is encapsulate the data access operation in a transaction, the Action Filter has several methods which the ASP.NET MVC framework executes in different stages of a request. In this case, we will use theOnActionExecuting which fires before the code enters into the controller method to start a transaction and OnResultExecuted which fires when the view is processed, we will commit/rollback based upon the status, here is the code that would process the action result in a transaction:
namespace AltNorthwind
{
using System.Web.Mvc;
using System.Transactions;
public class TransactionAttribute : ActionFilterAttribute
{
private CommittableTransaction transaction;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
transaction = new CommittableTransaction();
base.OnActionExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
try
{
if ((filterContext.Exception != null) && (!filterContext.ExceptionHandled))
{
transaction.Rollback();
}
else
{
transaction.Commit();
}
}
finally
{
transaction.Dispose();
}
}
}
}
Next, we will decorate the Controller Action method with this attribute like the following:
[Transaction]
public ActionResult Index()
{
return View(repository.All());
}
浙公网安备 33010602011771号