gpt4 book ai didi

c# - 从 ActionFilterAttribute 返回带有模型的 View

转载 作者:太空狗 更新时间:2023-10-30 00:47:01 25 4
gpt4 key购买 nike

当在强类型 View 上使用内置验证助手实现错误处理时,您通常会在 Controller 中创建一个 try/catch block ,并返回一个 View 及其对应的模型作为 的参数View() 方法:


Controller

public class MessageController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Models.Entities.Message message)
{
try
{
// Insert model into database
var dc = new DataContext();
dc.Messages.InsertOnSubmit(message);
dc.SubmitChanges();

return RedirectToAction("List");
}
catch
{
/* If insert fails, return a view with it's corresponding model to
enable validation helpers */
return View(message);
}
}
}



观点

<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<Models.Entities.Message>" %>

<%= Html.ValidationSummary("Fill out fields marked with *") %>

<% using (Html.BeginForm()) { %>

<div><%= Html.TextBox("MessageText") %></div>

<div><%= Html.ValidationMessage("MessageText", "*") %></div>

<% } %>



我已经以 ActionFilterAttribute 的形式实现了一个简单的错误处理程序,它将能够重定向到一个通用错误 View ,或者重定向到抛出异常的 View ,并让验证助手活跃起来。

这是我的 ActionFilterAttribute 的样子:

public class ErrorLoggingAttribute : ActionFilterAttribute, IExceptionFilter
{
private Boolean _onErrorRedirectToGenericErrorView;

/// <param name="onErrorRedirectToGenericErrorView">
/// True: redirect to a generic error view.
/// False: redirect back the view which threw an exception
/// </param>
public ErrorLoggingAttribute(Boolean onErrorRedirectToGenericErrorView)
{
_onErrorRedirectToGenericErrorView = onErrorRedirectToGenericErrorView;
}

public void OnException(ExceptionContext ec)
{
if (_onErrorRedirectToGenericErrorView)
{
/* Redirect back to the view where the exception was thrown and
include it's model so the validation helpers will work */
}
else
{
// Redirect to a generic error view
ec.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{"controller", "Error"},
{"action", "Index"}
});

ec.ExceptionHandled = true;
}
}
}

重定向到抛出异常的 View 相当简单。但问题在于:为了让验证助手工作,您需要为 View 提供它的模型。

如何返回抛出异常的 View 并为 View 提供相应的模型? (在本例中 Models.Entities.Message)。

最佳答案

我让它工作了!

出于某些奇怪的原因,我需要做的就是将 ViewData 传递给新的 ResultView

完整代码如下:

public class ErrorLoggingAttribute : ActionFilterAttribute, IExceptionFilter
{
private String _controllerName, _actionName;
private Boolean _redirectToGenericView = false;


public ErrorLoggingAttribute()
{
}


public ErrorLoggingAttribute(String actionName, String controllerName)
{
_controllerName = controllerName;
_actionName = actionName;
_redirectToGenericView = true;
}


void IExceptionFilter.OnException(ExceptionContext ec)
{
// log error

if (_redirectToGenericView)
{
ec.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{"controller", _controllerName},
{"action", _actionName}
});
}
else
{
ec.Result = new ViewResult
{
ViewName = ((RouteData) ec.RouteData).Values["action"].ToString(),
TempData = ec.Controller.TempData,
ViewData = ec.Controller.ViewData
};
}

ec.ExceptionHandled = true;
}
}


用法


以下是如何在 Controller 操作上使用该属性,以重定向到相同的 View (它是关联的模型)以在发生异常时启用标准验证助手:

[ErrorLogging]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Models.Entities.Message message)
{
var dc = new Models.DataContext();
dc.Messages.InsertOnSubmit(message);
dc.SubmitChanges();

return RedirectToAction("List", new { id = message.MessageId });
}

下面是发生异常时如何使用该属性重定向到通用 View :

[ErrorLogging("ControllerName", "ViewName")]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Models.Entities.Message message)


这是逻辑的完全分离。 Controller 中只有最基本的内容。

关于c# - 从 ActionFilterAttribute 返回带有模型的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1669553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com