ASP.NET MVC 4,在将视图模型对象用作操作方法参数之前如何访问/修改视图模型对象(并更改视图和操作方法)?

2023-12-29

ASP.NET MVC (MVC4) 中是否有任何有用的挂钩,可以让您在调用操作方法之前访问操作方法参数(视图模型),然后也可以(例如,取决于您在操作方法中检查的内容的值)参数)让您阻止调用操作方法,即将视图模型对象(操作方法参数)转发到另一个操作方法或直接转发到某个视图(即不在操作方法中进行任何进一步处理)?

如果您不明白这个问题,请参阅下面的代码示例,它应该说明我正在寻找的代码类型...... (虽然我不知道是否真的存在这种接口以及将实现挂钩到 MVC 框架的可能性)

如果这确实可能,我希望看到一个带有关于如何执行此操作的代码示例的答案(而不仅仅是某人声称的响应,例如“尝试使用方法'ActionFilterAttribute.OnActionExecuting'或'IModelBinder.BindModel'”,因为我已经尝试过这些但无法使其工作)。 另外,请尊重我不希望这个帖子成为关于WHY想做,但想看看HOW去做吧。 (也就是说,我没有兴趣参与诸如“您实际上想要实现什么目标?”或“做您想做的事情可能有更好的事情......”等回复的讨论。)

这个问题可以分为三个子问题/代码示例,正如我自己的代码示例下面试图说明的那样: (但希望它们“重构”为REAL使用实际现有类型的代码) (显然,下面包含子字符串“Some”的每种类型都是我编造的,我正在寻找相应的真实事物......)

(1) 在使用视图模型对象参数调用实际操作方法之前,如何在通用位置访问(并可能修改)视图模型对象(操作方法参数)的示例。

我正在寻找的代码示例可能类似于下面的代码,但不知道要使用哪种接口以及如何注册它才能执行如下所示的操作:

public class SomeClass: ISomeInterface { // How to register this kind of hook in Application_Start ?
  public void SomeMethodSomewhere(SomeActionMethodContext actionMethodContext, object actionMethodParameterViewModel) {
    string nameOfTheControllerAboutToBeInvoked = actionMethodContext.ControllerName;
    string nameOfTheActionMethodAboutToBeInvoked = actionMethodContext.MethodName;
    // the above strings are not used below but just used for illustrating that the "context object" contains information about the action method to become invoked by the MVC framework
    if(typeof(IMyBaseInterfaceForAllMyViewModels).IsAssignableFrom(actionMethodParameterViewModel.GetType())) {
        IMyBaseInterfaceForAllMyViewModels viewModel = (IMyBaseInterfaceForAllMyViewModels) actionMethodParameterViewModel;
        // check something in the view model:
        if(viewModel.MyFirstGeneralPropertyInAllViewModels == "foo") {
            // modify something in the view model before it will be passed to the target action method
            viewModel.MySecondGeneralPropertyInAllViewModels = "bar";
        }
    }
  }
}

(2) 如何阻止执行目标操作方法并调用另一个操作方法的示例。 该示例可能是上面示例的扩展,如下所示:

    public void SomeMethodSomewhere(SomeActionMethodContext actionMethodContext, object actionMethodParameterViewModel) {
        ... same as above ...
        if(viewModel.MyFirstGeneralPropertyInAllViewModels == "foo") {
            actionMethodContext.ControllerName = "SomeOtherController";
            actionMethodContext.MethodName = "SomeOtherActionMethod";
            // The above is just one example of how I imagine this kind of thing could be implemented with changing properties, and below is another example of doing it with a method invocation:
            SomeHelper.PreventCurrentlyTargetedActionMethodFromBecomingExecutedAndInsteadExecuteActionMethod("SomeOtherController", "SomeOtherActionMethod", actionMethodParameterViewModel);
            // Note that I do _NOT_ want to trigger a new http request with something like the method "Controller.RedirectToAction"
        }           

(3) 示例如何阻止执行正常操作方法,而是将视图模型对象直接转发到视图而不进行任何进一步处理。

该示例是上面第一个示例的扩展,如下所示:

    public void SomeMethodSomewhere(SomeActionMethodContext actionMethodContext, object actionMethodParameterViewModel) {
        ... same as the first example above ...
        if(viewModel.MyFirstGeneralPropertyInAllViewModels == "foo") {
            // the below used razor view must of course be implemented with a proper type for the model (e.g. interface 'IMyBaseInterfaceForAllMyViewModels' as used in first example above)
            SomeHelper.PreventCurrentlyTargetedActionMethodFromBecomingExecutedAndInsteadForwardViewModelToView("SomeViewName.cshtml", actionMethodParameterViewModel);
        }

您可以使用操作过滤器并覆盖OnActionExecuting event:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ...            
    }
}

现在让我们看看您可以从中提取哪些有用的信息filterContext传递给此方法的参数。您应该寻找的财产称为ActionParameters http://msdn.microsoft.com/en-us/library/system.web.mvc.actionexecutingcontext.actionparameters%28v=vs.98%29.aspx并代表一个IDictionary<string, object>。顾名思义,该属性包含按名称和值传递给控制器​​操作的所有参数。

因此,我们假设您有以下控制器操作:

[MyActionFilter]
public ActionResult Index(MyViewModel model)
{
    ...
}

以下是在模型绑定后检索视图模型的值的方法:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var model = filterContext.ActionParameters["model"] as MyViewModel;
        // do something with the model
        // You could change some of its properties here
    }
}

现在让我们看看你问题的第二部分。如何短路控制器动作并重定向到另一个动作?

这可以通过为Result财产:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    {
        ... some processing here and you decide to redirect:

        var routeValues = new RouteValueDictionary(new
        {
            controller = "somecontroller",
            action = "someaction"
        });
        filterContext.Result = new RedirectToRouteResult(routeValues);
    }
}

或者例如您决定缩短控制器操作的执行并直接渲染视图:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var viewResult = new ViewResult
        {
            ViewName = "~/Views/FooBar/Baz.cshtml",
        };
        MyViewModel someModel = ... get the model you want to pass to the view
        viewResult.ViewData.Model = model;
        filterContext.Result = viewResult;
    }
}

或者您可能决定呈现 JSON 结果:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        MyViewModel someModel = ... get the model you want to pass to the view
        filterContext.Result = new JsonResult
        {
            Data = model,
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
}

正如您所看到的,您可以做的事情的可能性是无限的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET MVC 4,在将视图模型对象用作操作方法参数之前如何访问/修改视图模型对象(并更改视图和操作方法)? 的相关文章

  • 我无法使 ValidateInput(False) 工作 - 从客户端检测到潜在危险的 Request.Form 值

    我尝试了很多组合 但无法在此代码块上关闭验证 ValidateInput false public ActionResult aSavePageCopy aLoggedIn int id Convert ToInt32 Request Fo
  • 相对于路径匹配路由

    我想要任何以以下结尾的网址 templates filename 使用路由属性映射到特定控制器 例如 public class TemplateController Controller Route templates templateFi
  • 无法将数据加载到 mvc 4 中的 jTable 中

    好的 我第一次尝试 jTable 我可以加载表 但这对我没有什么好处 因为它不会加载我的任何数据 当我调试程序时 我想要的表中的所有行都存储在我的列表中 因此我很困惑为什么当我运行应用程序时会弹出一个对话框 显示 与服务器通信时发生错误 H
  • Html Helper“操作”未定义,Asp.NET Core 2.2

    我是 ASP NET Core MVC 的新手 我会在这个问题前说我已经阅读了其他类似的问题 但它们与我遇到的问题并不完全相同 我正在尝试实现动态左侧导航 其中每个按钮都是从我的数据库加载的 当我打电话时 Html Action NavMe
  • ASP.NET MVC 中的经典 ASP (C#)

    我有一个应用程序想要 最终 转换为 ASP NET MVC 我想要进行全面的服务升级 到 ASP NET 但想要使用当前的 ASP 内容来运行当前的功能 这样我就可以在对新框架进行增量升级的同时升级小部分 该站点严重依赖于不太成熟的 VB6
  • 一个模型可以通过多个编辑器模板传递吗?

    我尝试使用编辑器模板显示视图模型 该模板在应用基本对象编辑器模板之前将模型包装在字段集中 My view model Mvc3VanillaApplication Models ContactModel using Html BeginFo
  • 如何使用 ASP.NET MVC 编辑多选列表?

    我想编辑一个如下所示的对象 我希望用 UsersGrossList 中的一个或多个用户填充 UsersSelectedList 使用 mvc 中的标准编辑视图 我只得到映射的字符串和布尔值 下面未显示 我在 google 上找到的许多示例都
  • ASP.NET MVC 开源真实世界应用程序 [已关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 每当我开始学习新技术或语言时 我倾向于查看一些 现实世界 应用程序的源代码 我发现它们对于理解常见的
  • MVC3 Controller 文件夹不会出现在 URL 中

    这只是一个例子 我不知道如何让它工作 在我的 MVC3 控制器文件夹中 如果我添加一个名为 Admin 的新文件夹 并添加一个带有操作 Index 的控制器 News 则当您尝试打开该 url 404 时 您会收到服务器错误 http ur
  • 以字符串数组作为参数的操作

    我想调用与此 uri 类似的操作 http server controller action columns firstname columns lastname columns age 并像这样使用它 public ActionResul
  • 无法加载文件或程序集“System.Web.Razor”或其依赖项之一

    我在我的网站 Web 应用程序 中使用了 Umbraco 4 11 6 我的网站在 localhost 中工作 通过 Visual Studio 2012 和 IIS v7 进行测试 但是当我从互联网空间运行它时 出现错误 错误是 无法加载
  • 我可以在 Windows 服务中托管(自托管)WCF 服务并通过 http 公开它吗?

    我是 WCF 新手 这可能吗 如果通过外部 Web 应用程序使用它 最好使用 IIS 和 http 即由 ASP NET MVC 应用程序托管的服务 吗 是的 您可以在 Windows 服务中托管 WCF 服务 http msdn micr
  • 从 ApiController 中的 json 序列化中排除属性

    我试图在 Web ApiControllers 中排除属性被序列化为 JSON 我已经验证了以下 2 个场景的工作原理 我已在我希望排除的属性中包含以下属性 System Web Script Serialization ScriptIgn
  • ASP.NET MVC 站点中的覆盖视图不起作用

    我的解决方案中有一个单独的项目 其中包含一些控制器和编译的视图 我将这些控制器用作 MVC 应用程序中其他控制器的基类 并使用 RazorGenerator 编译视图 可以说B是具有非抽象操作方法的基本控制器一些动作返回视图 MyView
  • JavaScript 错误:MVC2 视图中的条件编译已关闭

    我试图在 MVC2 视图页面中单击时调用 JavaScript 函数 a href Select a JavaScript 函数 function SelectBenefit id code alert id alert code 这里 b
  • 在 MVC API 中使用 Microsoft Azure Active Directory 验证 OAuth 2.0 不记名令牌时出现 401

    我正在写一个MVC 中的 API 服务 没有视图 只有 API 我想使用通过 client credentials 流获取的 OAuth 2 0 令牌 两条腿的 OAuth 我创建了一个Azure 管理门户中的 ActiveDirector
  • ASP.NET Core 中间件与过滤器

    在阅读了 ASP NET Core 中间件之后 我对何时应该使用过滤器以及何时应该使用中间件感到困惑 因为它们似乎实现了相同的目标 什么时候应该使用中间件而不是过滤器 9频道有一个关于此的视频 ASP NET 怪物 91 中间件与过滤器 h
  • MVC - 没有具有“IEnumerable”类型键的 Viewdata 项目

    我是 MVC 和 ASP NET 的新手 希望学习一些知识 因此我尝试制作一些简单的应用程序来了解细节 好吧 我正在尝试制作一个下拉框显示书籍列表 其中显示书名但发布 book id 主键 我得到的错误是 不存在键为 IEnumerable
  • 如何清除 ASP.NET MVC 应用程序中文本框的发布数据?

    默认情况下 使用 呈现的文本框使用发布数据中的值 例如如果页面上存在验证错误 将从发布的数据中检索该值并将其用于 value 属性 现在 在某些情况下 我希望能够清除该值 换句话说 我希望文本框为空 我不希望 MVC 从发布的数据中获取值并
  • 使用asp.net mvc计算相对日期

    在 C 中使用 ASP NET MVC 显示相对日期 例如 20 分钟前 的最佳库是什么 当简单的扩展方法可以做到这一点时 您就不需要库了 这是我使用过的扩展方法 public static string TimeAgo this Date

随机推荐