Как установить модель представления на ViewResult в фильтре запросов?
Я делаю проект 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.
Ответы
Ответ 1
ViewResult vr = new System.Web.Mvc.ViewResult
{
ViewName = this.View, //<======/Test/Test.cshtml
ViewData = new ViewDataDictionary(filterContext.Controller.ViewData)
{
Model = // set the model
}
};
Ответ 2
из источника asp.net mvc, они просто устанавливают модель в виде данных.
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
};
}
Ответ 3
Вы можете изменить контекст фильтра и установить View, Model, ViewData и все, что хотите. Вы должны учитывать некоторые вещи:
// 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 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;
Таким образом, ваш View получит модель, если пожелает.
Ответ 4
Свойство модели действительно представляет собой только ViewDataDictionary, вы можете инициализировать экземпляр этого с вашей фактической моделью i.e.
vr.Model = new ViewDataDictionary(model);
Ответ 5
Вы можете получить контроллер из filtercontext и использовать метод View на контроллере, например так:
filterContext.Result = (filterContext.Controller as Controller).View(model);