asp.net 如何在C#中为当前URL添加一个参数

rjzwgtxy  于 2023-05-02  发布在  .NET
关注(0)|答案(3)|浏览(283)

我有2个链接

<li class="active">
  <a href="<%#CurrentSearchUrl%>"><span>Current search Page
 </span></a> 

  <li><a href="<%#CurrentSearchUrlParam%>"><span>Add param </span>
      </a>

在Page_Load

CurrentSearchUrl = Request.Url.AbsoluteUri;
    CurrentSearchUrlParam = Request.Url+"&discount=1";

param被添加但是url不正确我的当前url是

http://localhost:1067/search/default.aspx?q=test

我想添加一个参数,所需的结果应该是

http://localhost:1067/search/default.aspx?q=test&discount=1

先谢谢你了

wgx48brx

wgx48brx1#

var uriBuilder = new UriBuilder(Request.Url.AbsoluteUri);
var paramValues = HttpUtility.ParseQueryString(uriBuilder.Query);
paramValues.Add("param1", "value1");
paramValues.Add("param2", "value2");
uriBuilder.Query = paramValues.ToString();

Link1.HRef=uriBuilder.Uri;
6xfqseft

6xfqseft2#

注意已经存在的参数。下面是维克托代码的一个小修改:

var uriBuilder = new UriBuilder(Request.Url.AbsoluteUri);
var paramValues = HttpUtility.ParseQueryString(uriBuilder.Query);

if(paramValues.Get("param1")!=null) paramValues.Remove("param1");
paramValues.Add("param1", "value1");
paramValues.Add("param2", "value2");
uriBuilder.Query = paramValues.ToString();

Link1.HRef=uriBuilder.Uri;
kqhtkvqz

kqhtkvqz3#

有很多方法可以做到这一点。例如:
您的HTML:

<li class="active">
  <a href="" runat="server" ID="Link1"><span>Current search Page
 </span></a> 

  <li><a href="" runat="server" ID="Link2"><span>Add param </span>
      </a>

在Page_Load中:

Link1.HRef = HttpContext.Current.Request.Url.ToString();
Link2.HRef = HttpContext.Current.Request.Url.ToString()+"&discount=1";

相关问题