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.
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. 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 }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With