I’ve tried to do something from another post, didn’t work.
How do I combine those two codes?
HTML CODE:
@using Microsoft.AspNetCore.Identity
@using SvivaTeamVersion3.Areas.Identity.Data
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
<p><button onclick="" class="w3-button w3-padding-large w3-white w3-border"><b>ADD NEW REPORT »</b></button></p>
Code that I want to add to the onclick event:
if (SignInManager.IsSignedIn(User))
{
<script>
window.location.href = "http://stackoverflow.com";
</script>
} else {
<script>
window.location.href = "http://stackoverflow.com";
</script>
}
Controller (Home Controller) – I added here the checkLoginStatus function to handle the problem right now :
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SvivaTeamVersion3.Models;
using System.Diagnostics;
namespace SvivaTeamVersion3.Controllers
{
//[Authorize]
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public ActionResult CheckLoginStatus()
{
if (!User.Identity.IsAuthenticated)
return Redirect("/Identity/Account/Login");
return View("~/Views/Report/Create.cshtml");
}
}
}
2
Answers
As I understood that you need a conditional access to your page based on User authentication state, so this should work:
A better approach would be to use
OnGet()
method in your razor page model:Update: based on the update to question your application is using MVC. So, for authentication it’s would be easier to use the
[Authorize]
attribute. I’ll assume that yourCreate
pageexists in
ReportController
according to view path provided in your question:This will prevent anonymous users from accessing that page without authentication, or you can do any other logic required before returning the view and based on that redirect to another page.
Otherwise, you can use a form and submit to specific action in your controller then execute whatever logic you need:
It’s easier to use
RedirectToAction("Create", "Report")
when redirecting internally between controllers/actions and useRedirect()
for external links.If you want to use c#code in js,you can try to use: