簡體   English   中英

如何將 HTML 與 C# 鏈接

[英]how to link HTML with C#

我試圖從另一個帖子中做一些事情,但沒有奏效。 我如何結合這兩個代碼? 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>

我想添加到 onclick 事件的代碼:

if (SignInManager.IsSignedIn(User))
    {
        <script>
            window.location.href = "http://stackoverflow.com";
        </script>
    } else {
        <script>
            window.location.href = "http://stackoverflow.com";
        </script>
    }

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");
        }
    }
}

據我了解,您需要基於用戶身份驗證 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>
}

更好的方法是在 razor 頁面 model 中使用 OnGet() 方法:

public IActionResult OnGet()
{
    if(SignInManager.IsSignedIn(User))
        Redirect("http://stackoverflow.com");
    else
        Redirect("http://stackoverflow.com");
}

如果你想在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM