【问题标题】:Change URL when I change dropdown item selected in asp.net 4.0当我更改在 asp.net 4.0 中选择的下拉项时更改 URL
【发布时间】:2015-09-27 09:56:16
【问题描述】:

我想在选择下拉项目时更改 ASP.Net 中的 URL。例如“www.website.com”,我想在 URL 中显示状态,如“www.website.com/Maharastra”。 如果我现在选择地区,我想将我的 URL 显示为“www.website.com/Maharastra/Mumbai”。

默认情况下,当页面最初加载时,我在列表视图中显示所有状态的列表,并实现了工作正常的 URL 重写概念。我想以相同的方式为下拉列表实现它。怎么做

在 Global.asax 中

void Application_Start(object sender, EventArgs e)
{
        // Code that runs on application startup
        RegisterRoutes(RouteTable.Routes);
    }
    void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("StateRoute", "{StateName}", "~/Default.aspx", false, new RouteValueDictionary { { "StateName", String.Empty } });
        routes.MapPageRoute("DistrictRoute", "{StateName}/{DistrictName}", "~/State.aspx", false, new RouteValueDictionary { { "StateName", String.Empty }, { "DistrictName", String.Empty } });
}

在 Default.aspx 中

protected void Page_Load(object sender, EventArgs e)
{
  if (this.Page.RouteData.Values["StateName"] != null)
  {
      dlstState.SelectedIndex = -1;
      dlstState.Items.FindByText(this.Page.RouteData.Values["StateName"].ToString()).Selected = true;
      dlstState_SelectedIndexChanged(null, null);
  }
  if (this.Page.RouteData.Values["DistrictName"] != null)
  {
      dlstDistrict.SelectedIndex = -1;
      dlstDistrict.Items.FindByText(this.Page.RouteData.Values["DistrictName"].ToString()).Selected = true;
      dlstDistrict_SelectedIndexChanged(null, null);
  }
}

【问题讨论】:

  • URL 是只读的。你不能像他们这样

标签: c# asp.net url-rewriting


【解决方案1】:

是的,你可以用 javascript 来做。看看这个函数:

window.history.pushState("object or string", "Title", "/new-url");

执行这行代码会将 URL 更改为 my-domain.com/new-url(第三个选项)。 Title 字符串(第二个选项)旨在描述新状态,并且不会像人们预期的那样更改文档的标题 (for more detail)

因此,在您的情况下,只需获取下拉列表中的值并使用 .pushState 函数,如下所示:

windows.history.pushState({}, null, <your_new_URL_here>);

阅读有关操纵浏览器历史记录的更多信息 here(其中包含有关 pushState 的信息)。

【讨论】:

  • 我在 Javascript 中尝试过。但是 ASP.Net 正在覆盖 URL。能否请您在 ASP.Net 中提供解决方案
  • 我不知道为什么 ASP.NET 会覆盖你的 URL。请看看这个post
猜你喜欢
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多