开发者

ASP.NET User Controls and Information Passing

I have written a user control that contains a text box and a button. Functionality is such that you input a QuoteID into the textbox and click the button then the app goes and fetches a bunch of information about the specified quote and plops it onto the screen.

My employer wants this to be modified to be only a button which will reside on the page t开发者_开发技巧hat displays the order normally. So, obviously on this page we have access to the QuoteID. However, since the text-box is no longer part of the control I'm not sure how to get to the ID.

Is there any way to pass information into a custom control? Perhaps a way to set up the HTML so that the control knows what ID it will be searching for if clicked?

We are not using MVC.


You can add a public property to the user control for the QuoteID and set it whenever you know what it is.

Example:

//code behind of your user control
class SpecialUserControl: UserControl
{
    //this property is now accessible outside this user control
    public int QuoteID { get; set; }

}


You could always save the ID as a query string in the url, then retrieve it in the code behind file. It should then be accessible from the HTML. This would depend on how sensitive the ID was though, as it would be viewable in the address bar.

string ID = Request.QueryString[1];

That would help with the extraction process, and from there simply pass the ID to wherever its needed in the code behind file.


A public property in the user control is the way to go.

public string QuoteID { get; set; }

You can assign it from the page, or from the code behind.

<uc1:QuoteControl id="QuoteControl1" runat="server" QuoteID="myquoteid" />

or

QuoteControl1.QuoteID = "myquoteid";


Just add a propert in the user control:

public string MyQuote
{
get
{
    return txtQuote.Text;
}
set
{
    txtQuote.Text = value;
}
}

Then you can access it from your page as:

<uc1:Quote id="QuoteUserControl" runat="server" />

string quote = QuoteUserControl.MyQuote;


asp:HiddenField controls might work out for you here.


In your page load method, you can pass the property to the user control - something like this example (where we set a hidden label to be the quote id for use when you press the button...)

Control c = LoadControl("QuoteSearch.ascx");
Label hiddenLabel = (Label)c.FindControl("HiddenQuoteIdLabelOrWhatever");
hiddenLabel .Text = "32415";

Although, you have to ask yourself whether a user control is really any use at this stage as it doesn't sound like the nice re-usable, stand-alone quote search box that you originally designed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜