Call Method in Controller from View(Cshtml)

Call a controller method in a view

You may move that logic to a separate class. Since this code is using HttpContext.Session, it is a good idea to create an interface for your class and let this class be your concrete implementation using HttpContext.Session. You can inject the needed implementation in your controller or view using the Dependency Injection framework.

public interface IUserAccessHelper
{
bool IsInRole(string role);
}
public class UserAccessHelper : IUserAccessHelper
{
private readonly IHttpContextAccessor httpContextAccessor;

public UserAccessHelper(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
public Boolean IsInRole(string role)
{
Boolean roleMembership = false;

if (httpContextAccessor.HttpContext.Session.GetInt32("ID") != null)
{
if (httpContextAccessor.HttpContext.Session.GetString("Role") == role)
{
roleMembership = true;
}
}
return roleMembership;
}
}

Now make sure to to register this in the ConfigureServices method in Startup.cs

services.AddTransient<IUserAccessHelper, UserAccessHelper>();

Now in the razor view, you can inject this dependency. Yes, DI is possible in views now :)

@inject IUserAccessHelper UserAccessHelper
@if (UserAccessHelper.IsInRole("SomeRole"))
{
<h2>In Role</h2>
}
else
{
<h2>Not in Role</h2>
}

You can inject the same IUserAccessHelper inside your controller via constructor injection.

public class HomeController : Controller
{
private readonly IUserAccessHelper userAccessHelper;
public HomeController(IUserAccessHelper userAccessHelper)
{
this.userAccessHelper = userAccessHelper;
}
public ActionResult Create()
{
// you can use this.userAccessHelper.IsInRole("abc")
// to do :return something
}
}

Since you are injecting the needed implementation via dependency injection, now you can unit test your controller method. Your controller code does not have any tight coupling to HttpContext now. You can create a MockUserAccessHelper (which does not use HttpContext) for your unit tests and use that as needed.

Simplest way to call a controller method from a view button in .Net (mvc)

You can use set href path to call your controller from view.

<a class="btn btn-success" href="@Url.Action("Start", "DefaultController")">Start</a>

and if want to pass parameter then:

<a class="btn btn-success" href="@Url.Action("Start","DefaultController", new {id=Item.id })">Start</a>

or for other options you can check this link

you can call your controller method using ajax also refer this link



Related Topics



Leave a reply



Submit