简体   繁体   中英

Net Core 2.0 pass data from IPageFilter Attribute to Razor Pages PageModel

How can i pass data(object) from IPageFilter Attribute to Razor Page PageModel. Can i create a ViewData["example"] = object in this filter?

I can do it like this;

    public void OnPageHandlerSelected(PageHandlerSelectedContext context)
    {
         //i want like this
        //ViewData["Member"] = memberUser;

        context.HttpContext.Items.Add("Member", memberUser);
    }

But i must get everytime this object from Items.

Any way can i do this work with ViewData or TempData ?

Unfortunately not. ViewData and TempData are only relevant to a PageResult and the filter pipeline doesn't even know what the Result will be.

The annoying thing is that the PageContext , which is used to create the PageHandlerXXXXContext , does have a ViewData property but you can't access it from the IPageFilter .

You can access the selected PageModel through the context's HandlerInstance property, like this:

public void OnPageHandlerSelected(PageHandlerSelectedContext context) {
    var pageModel = context.HandlerInstance as PageModel ??
        throw new Exception("This page filter must run in a PageModel.");

    pageModel.ViewData["Member"] = memberUser;
    ...
}

Considering that a IPageFilter is for Razor Pages only, I cannot see how HandlerInstance could ever be anything except a PageModel, but if anyone knows otherwise please correct me.

If you not define page model class for page then "HandlerInstance as PageModel" is always be null. In this case need to check as Page:

public async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
    PageContext pageContext = null;

    if (context.HandlerInstance is Page page) { pageContext = page.PageContext; }
    else if(context.HandlerInstance is PageModel pageModel) { pageContext = pageModel.PageContext; }

    if (pageContext != null)
    {
        pageContext.ViewData["UserEmail"] = "email";
    }

    await next.Invoke();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM