gpt4 book ai didi

c# - 如何在请求过滤器的 ViewResult 上设置 View 模型?

转载 作者:IT王子 更新时间:2023-10-29 04:47:42 27 4
gpt4 key购买 nike

我制作了一个 MVC 项目,我想将模型设置为来自过滤器的 View 。

但是我不知道,我该怎么做。

模型:

public class TestModel
{
public int ID { get; set; }
public string Name { get; set; }
}

Controller :

[CustomFilter(View = "../Test/Test")]//<===/Test/Test.cshtml
public ActionResult Test(TestModel testModel)//<===Model from Page
{
//the Model has Value!!
// if has some exception here
return View(model);//<=====/Test/Test.cshtml
}

过滤器(只是演示):

public override void OnActionExecuting(ActionExecutingContext filterContext){
ViewResult vr = new System.Web.Mvc.ViewResult()
{
ViewName = this.View,//<======/Test/Test.cshtml
ViewData = filterContext.Controller.ViewData
};
//How can I set Model here?!!
vr.Model = ???? //<========the Model is only get
filterContext.Result = vr;
}

编辑开始感谢@Richard Szalay @Zabavsky @James @spaceman

更改过滤器扩展到 HandleErrorAttribute

  ViewResult vr = new System.Web.Mvc.ViewResult()
{
ViewName = this.View,//<======/Test/Test.cshtml
ViewData = new ViewDataDictionary(filterContext.Controller.ViewData)
{
//I want get testModel from Action's paramater
//the filter extends HandleErrorAttribute
Model = new { ID = 3, Name = "test" }// set the model
}
};

编辑结束

测试/测试.chtml

@model TestModel
<h2>Test</h2>
@Model //<=====model is null

当我请求时

http://localhost/Test/Test?ID=3&Name=4

测试页获取不到模型

最佳答案

ViewResult vr = new System.Web.Mvc.ViewResult
{
ViewName = this.View, //<======/Test/Test.cshtml
ViewData = new ViewDataDictionary(filterContext.Controller.ViewData)
{
Model = // set the model
}
};

关于c# - 如何在请求过滤器的 ViewResult 上设置 View 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20042739/

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