Я делаю проект MVC, и я хочу установить Model в View из фильтра.
Но я не знаю, как я могу это сделать.
Модель:
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
}
фильтр (только демо):
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 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
Страница тестирования не может получить Model.