Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set view model on ViewResult in request filter?

Tags:

I make a MVC project and I want set Model into View from filter.

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:

[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

change filter extends to 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

@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.

like image 437
zt9788 Avatar asked Nov 18 '13 07:11

zt9788


2 Answers

ViewResult vr = new System.Web.Mvc.ViewResult     {         ViewName = this.View, //<======/Test/Test.cshtml         ViewData = new ViewDataDictionary(filterContext.Controller.ViewData)             {                 Model = // set the model             }     }; 
like image 196
Zabavsky Avatar answered Sep 27 '22 19:09

Zabavsky


from the asp.net mvc source, they just set the model in view data. 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         };     } 
like image 30
spaceman Avatar answered Sep 27 '22 17:09

spaceman