[英]how to link HTML with C#
I've tried to do something from another post, didn't work.我试图从另一个帖子中做一些事情,但没有奏效。 How do I combine those two codes?
我如何结合这两个代码? HTML CODE:
HTML 代码:
@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:我想添加到 onclick 事件的代码:
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: Controller(家庭控制器) - 我在这里添加了 checkLoginStatus function 来立即处理问题:
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");
}
}
}
As I understood that you need a conditional access to you page based on User authentication state, so this should work:据我了解,您需要基于用户身份验证 state 有条件地访问您的页面,所以这应该有效:
@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>
@if (SignInManager.IsSignedIn(User))
{
<script>
window.location.href = "http://stackoverflow.com";
</script>
} else {
<script>
window.location.href = "http://stackoverflow.com";
</script>
}
A better approach would be to use OnGet() method in your razor page model:更好的方法是在 razor 页面 model 中使用 OnGet() 方法:
public IActionResult OnGet()
{
if(SignInManager.IsSignedIn(User))
Redirect("http://stackoverflow.com");
else
Redirect("http://stackoverflow.com");
}
If you want to use c#code in js,you can try to use:如果你想在 js 中使用 c#code,你可以尝试使用:
<script>
var url;
$(function(){
url=@SignInManager.IsSignedIn(User)?"url1":"url2";
window.location.href =url;
})
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.