我制作了一个 MVC 项目,我想从过滤器中将模型设置为视图。
但我不知道,我该怎么做。
该模型:
public class TestModel
{
public int ID { get; set; }
public string Name { get; set; }
}
控制器:
[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
}
};
编辑结束
测试/Test.chtml
@model TestModel
<h2>Test</h2>
@Model //<=====model is null
当我要求
http://localhost/Test/Test?ID=3&Name=4
测试页无法获取模型。