Calling an async function in Razor View using the custom view base
In my MVC5 app, some view components don't show up in RAZOR if the user doesn't have permissions for it.
Permissions are selected using the repository pattern, which is completely asynchronous like the rest of my application.
I have implemented an IPermission service that has the following methods.
public interface IPermissionService
{
Task<bool> IsUserAllowed(string moduleName, string action);
Task<bool> IsUserAdmin();
}
Now, to be able to use this service in my view, I wrote a custom view base that inherits from WebViewPage as follows:
public abstract class ViewBase<T> : WebViewPage<T> where T : class
{
public IPermissionService Permissions;
public override void InitHelpers()
{
base.InitHelpers();
Permissions= DependencyResolver.Current.GetService<IPermissionService>();
}
public override void Execute()
{
}
}
I cannot use these async functions from my view as await doesn't work there. I don't want to create a separate non-asynchronous implementation of data repositories. Also I feel like calling async function without waiting, doing something like Task.Result () is also not very good at calling async method without waiting # 2
Is there a better way to do this?
source to share
You can try decoupling the loading of these resources from the loading of your view.
Your view should have loaded all items that are allowed to all users.
When the view is rendered on the client side, send an asynchronous async call back to an activity on the server that will evaluate that the user has view permission and return the appropriate data / models to load on the client side.
This way you don't have to worry about running the asynchronous server code in the view and still have full control over what the user can see (as well as asynchronously)
source to share
This seems like a good candidate for addiction. For example, check out Autofac's suggestions for entering properties:
http://docs.autofac.org/en/latest/integration/mvc.html#enable-property-injection-for-view-pages
source to share