简体   繁体   English

如何在请求过滤器中的ViewResult上设置视图模型?

[英]How to set view model on ViewResult in request filter?

I make a MVC project and I want set Model into View from filter. 我创建了一个MVC项目,我想从过滤器中将模型设置为View。

But I do not kown ,How can I do this. 但我不知道,我怎么能这样做。

the Model: 该模型:

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

Contorller: Contorller:

[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
}

filter(just demo): 过滤器(只是演示):

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;
}

Edit begin thanks for @Richard Szalay @Zabavsky @James @spaceman 编辑开始感谢@Richard Szalay @Zabavsky @James @spaceman

change filter extends to HandleErrorAttribute 更改过滤器扩展到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
            }                             
      };

Edit end 编辑结束

Test/Test.chtml 测试/ Test.chtml

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

when I request 当我要求时

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

The Test Page can not get Model. 测试页无法获得模型。

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

from the asp.net mvc source, they just set the model in view data. 从asp.net mvc源代码,他们只是在视图数据中设置模型。 http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Controller.cs http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Controller.cs

 protected internal virtual ViewResult View(string viewName, string masterName, object model)
    {
        if (model != null)
        {
            ViewData.Model = model;
        }

        return new ViewResult
        {
            ViewName = viewName,
            MasterName = masterName,
            ViewData = ViewData,
            TempData = TempData,
            ViewEngineCollection = ViewEngineCollection
        };
    }

You can modify the filter context, and set the View, the Model, the ViewData and whatever you want. 您可以修改过滤器上下文,并设置View,Model,ViewData以及您想要的任何内容。 You have to take some things into account: 你必须考虑一些事情:

// You can specify a model, and some extra info, like ViewBag:
ViewDataDictionary viewData = new ViewDataDictionary
{
    Model = new MyViewModel
    {
        ModelProperty = ...,
        OtherModelProperty = ...,
        ...
    } 
};

// You can take into account if it's a partial or not, to return a View 
// or Partial View (casted to base, to set the remaining data):
ViewResultBase result = filterContext.IsChildAction
    ? new PartialViewResult()
    : (ViewResultBase) (new ViewResult());

// Set the remaining data: Name of the View, (if in Shared folder) or
// Relative path to the view file with extension, like "~/Views/Misc/AView.cshtml"
result.ViewName = View;                     
result.ViewData = viewData;     // as defined above

// Set this as the result
filterContext.Result = result;  

In this way, your View will receive the model, as desired. 这样,您的View将根据需要接收模型。

model属性实际上只是一个ViewDataDictionary,你可以用你的实际模型初始化它的实例,即

vr.Model = new ViewDataDictionary(model);

您可以从filtercontext获取控制器并在控制器上使用View方法,如下所示:

filterContext.Result = (filterContext.Controller as Controller).View(model);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#mvc4 ViewResult如何设置控制器和区域? - C# mvc4 ViewResult how to set controller and area? params ViewResult[] 将相同的模型应用于作为参数传递的所有 ViewResult 实例 - params ViewResult[] applying the same model to all instances of ViewResult passed as arguments 在当前 ViewResult 的每个部分视图上设置 ViewContext 属性以禁用 jquery 不显眼的验证 HTML 属性生成 - Set a ViewContext property on every partial view of the current ViewResult to disable jquery unobtrusive validation HTML attribute generation 如何在视图中设置通用模型? - How to set a generic model in a view? 如何从ASP.NET MVC RC1中的ViewResult获取模型数据? - How to get model data from a ViewResult in ASP.NET MVC RC1? 如何使用StructureMap在视图模型上自动设置属性 - How to automatically set properties on view model with StructureMap 如何获取ViewResult的索引? - How can I get the Index of a ViewResult? 如何在运行时设置视图/视图模型数据模板? - How do I set view/view model data template at runtime? 查看与动作过滤器的模型 - View with model from action filter 如何通过使用身份验证筛选器将标头设置为令牌请求OAuth? - How to set header as token request OAuth by using authentication filter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM