How can I send an array of strings from one ASP.NE

2019-07-23 05:36发布

问题:

I now have two asp.net pages. When I click on a link on page A, I open the other one (let's call it page B). When I do this, I want to send some information from Page A to Page B in the form of an array of strings. This array is different depending on what link I follow on Page A.

I know I could send this information via the URL with the ?string1=bla1&string2=bla2 etc., but I don't want it that way, as it can get complicated if there are too many strings in the array.

I think there is something similar, like a POST in PHP, but how would that be in ASP?

Any help would be appreciated. Thanks.

Cheers!

回答1:

Just send the values in the URL. That's likely the most correct way to do it anyways. Information that specifies what to display on the page should go in the URL. Pack them into a comma separated string if you don't like going string1=&string2=.

Please don't abuse the session for this, unless you have an absurdly large amount of data to pass. In that case, store them in a dictionary in the session with a unique key and pass that in the URL. This avoids many unexpected problems with slow connections and tabbed browsing and crawlers and whatnot.



回答2:

You could just use session state. You'd populate it in the first page something like this

Page.Session["MyArray"] = new string[] {"one", "two", "three" };

Then retrieve the information in your target page with something like this:

string[] values = Page.Session["MyArray"] as string[];

Edit:

In response to your comment, you'd need to handle the OnClick event of your link buttons e.g.

<asp:LinkButton ID="myButton" Text="Click Me" OnClick="myButton_Click" runat="server"/>

then in your code behind, you'd need to set the session state as above e.g.

protected void myButton_Click(object sender, EventArgs e)
{
    Page.Session["MyArray"] = new string[] {"one", "two", "three" };
    Response.Redirect("~/AnotherPage.aspx");
}


回答3:

You could use a session variable or HttpContext like this: http://www.codedigest.com/Articles/ASPNET/76_HttpContext_Object_for_Developers.aspx



回答4:

If we are talking about pure link (a href) tag, there is no other option than putting it in querystring.

If you want to hack it about, you can capture the onclick event of those links and redirect them to your own event handler that will compose whatever you need to say... a hidden field and call the form post when the click event happens.

If it is a postback sort of thing, you can use Session as suggested in the other answer and do a redirect to the other page and pick up the Session from there.