如何从控制器 ASP.NET url 中删除哈希参数,以便返回到 Angular.JS 应用程序中的根 URI

How to remove hash parameters from url in ASP.NET controller in order to return to the root uri in an Angular.JS application?

本文关键字:返回 Angular JS URI 应用程序 参数 ASP 控制器 NET url 哈希      更新时间:2023-09-26

我正在 ASP.NET MVC5 C# 应用程序内创建一个 Angular.JS 页面,我想在新页面加载或浏览器页面刷新时从 URL 中删除 # 和尾随路径。

例如:www.example.com/calculator#/step2我希望它回到页面刷新时的简单www.example.com/calculator

这个想法是我需要它在新页面加载或浏览器页面刷新时在计算器窗体的开头重新启动它们。原因是我创建的表单不会在页面刷新之间保留数据,因此他们需要从头开始重新填充数据。

每当重新加载页面时,它都会调用我的 ASP.NET 计算器控制器,所以我的想法是服务器可以重置 URL 路径?

在我的 ASP.NET 计算器控制器中,我得到了:

public class CalculatorController : Controller
{
    // GET: Calculator
    public ActionResult Index()
    {
        // check for # sign and remove it and trailing path from URL.
        // or simply make the path "/calculator" every time.
        return View();
    }
}

有没有简单的方法可以做到这一点?我是Angular的新手.JS所以如果有Angular.JS解决这个问题的解决方案,我也很乐意听到。

根据发布的有用评论的建议,我为我的问题编写了一个解决方案。就像 davcs86 所说的那样,哈希后面的字符串只能在客户端处理。

使用Angular.JS以及Charlietfl建议的resolve,这就是我想出的:

var myApp = angular.module("app-calculator", ["calculatorControls", "ngRoute"])
    .config(function ($routeProvider) {
        $routeProvider.when("/", {
            controller: "termsController",
            controllerAs: "vm",
            templateUrl: "/content/templates/termsView.html"
        });
        $routeProvider.when("/condition", {
            controller: "conditionController",
            controllerAs: "vm",
            templateUrl: "/content/templates/conditionView.html",
            resolve: {
                validate: function ($location, Data) {
                    if (!Data.terms) {
                        $location.path('/');
                    }
                }
            }
        });
        $routeProvider.otherwise({ redirectTo: "/" });
    });

基本上,我使用resolve: { validate: ... }部分来检查我的Data.terms字段是否已完成。如果尚未设置该值(在浏览器页面刷新重置数据的情况下),则它将使用 $location.path('/'); 将重定向发送回根页面。否则,如果已设置 Data.terms,则它将加载请求的页面。

我也通过jquery解决了这个问题。我的链接是[http://localhost:53209/HarcamaIslemleri?toastMesaj=true],我想这样做[http://localhost:53209/HarcamaIslemleri?toastMesaj=false] 当我刷新页面时。

在jquery中,我写了这个代码块,它对我有用,我希望这个答案会有用

     $(document).ready(function () {  
       
         const queryString = window.location.search;
         if (queryString) {
             const urlParams = new URLSearchParams(queryString);
             const stepValue = urlParams.get('toastMesaj');
             if (stepValue == "true") {
                 toastr.warning('Successfully Added!');
                 window.history.replaceState(null, null, '?toastMesaj=' + false);
             }
  
         }
});