Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnActionExecuting constructing a partial view

Apologises if this is obvious, but I am trying to make the an attribute that handling a caching of the model used in a partial view.

  [MyCache(typeof(MyModel))]
  public ActionResult MyAction(string fooId)
  {
      return PartialView(new MyModel());
  }

My attribute is supposed to update the cache with the input model on post, and override the actions result on get with my cached model.

However I don't know how to call the PartialView method from outside the contoller. This constructor doesn't seem to have any arguments:

  new PartialViewResult(filterContext.HttpContext.Cache.Get("MyModelCache")[model.Name]);

How can I construct the model using the razor view? Thanks.

like image 986
Tim Avatar asked Dec 04 '25 18:12

Tim


2 Answers

filterContext.Controller.ViewData.Model = 
    filterContext.HttpContext.Cache.Get("MyModelCache")[model.Name];
filterContext.Result = new PartialViewResult
{
    ViewData = filterContext.Controller.ViewData,
    ViewName = "~/Views/_NameOfPartial", // optional if you need it
};

Here is the source of the PartialView method in a controller that takes 2 arguments:

namespace System.Web.Mvc
{
    public abstract class Controller : ControllerBase, (etc)
    {
        ...
        protected internal virtual PartialViewResult PartialView(
            string viewName, object model)
        {
            if (model != null)
                this.ViewData.Model = model;
            PartialViewResult partialViewResult = new PartialViewResult();
            partialViewResult.ViewName = viewName;
            partialViewResult.ViewData = this.ViewData;
            partialViewResult.TempData = this.TempData;
            partialViewResult.ViewEngineCollection = this.ViewEngineCollection;
            return partialViewResult;
        }
        ...
    }
}
like image 158
danludwig Avatar answered Dec 06 '25 08:12

danludwig


Try this

new PartialViewResult
{
    ViewData = new ViewDataDictionary(filterContext.HttpContext.Cache.Get("MyModelCache"))[model.Name],
}
like image 29
Sławomir Rosiek Avatar answered Dec 06 '25 07:12

Sławomir Rosiek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!