Postback from Dynamic Content - c#

I am dynamically building some HTML content on a WebForms page, using HtmlGenericControl().
HtmlGenericControl p = new HtmlGenericControl("p");
// ...
ListItems.Controls.Add(p);
But now I need to add a button to the paragraph created above, and the button needs to do a postback when clicked.
Must I completely rework this code to load child controls, which can contain real server-side buttons? Or is there a way to inject buttons capable of some type of postback?

Here's a test method and test EventHandler that, if called, will add a button control with a server-side Click event to ListItems. The commented-out code will change the markup of the ListItems object if InnerHtml is available but I rethought that approach and assumed the existence of a textbox on the page that would show the results of the click event firing. There are a number of concerns that you'll want to handle if you need those child controls to be present from one postback to another, though- for instance, if Test() isn't called every time the page loads that button won't be created and there will be no way to call its EventHandler unless other controls also call it.
public void Test()
{
System.Web.UI.HtmlControls.HtmlGenericControl p = new System.Web.UI.HtmlControls.HtmlGenericControl("p");
p.InnerHtml = #"<strong>Test</strong>";
// ...
ListItems.Controls.Add(p);
Button b = new Button();
b.ID = "cmdTest";
b.Text = "Test";
b.Click += new EventHandler(test_Click);
p.Controls.Add(b);
}
protected void test_Click(object sender, EventArgs e)
{
// ListItems.InnerHtml = "Test button clicked";
txtTestResults.Text = "Test button clicked at " + DateTime.Now.ToShortTimeString();
}

Related

ASP.Net Button and the onclick event don't work

I make a dynamic table with buttons in they cells, but when i click some button show me this error in console:
Uncaught ReferenceError: bttn_Click is not defined
at HTMLUnknownElement.onclick (VM51 panel.aspx:1)
this is how i make the button in html and asp.net :
StringBuilder htmlStr = new StringBuilder();
htmlStr.Append("<asp:button onclick='bttn_Click' class='btn btn-warning btn-xs' ID='Bttn_PDF'>PDF</asp:button>");
PlaceHolder1.Controls.Add(new Literal { Text = htmlStr.ToString() });
and the C#
protected void bttn_Click(object sender, CommandEventArgs e)
{
Button btn = (Button)sender;
string btnid = btn.CommandArgument;
test.Text = btnid;
}
This is because the onclick event actually expects a Javascript-specific event to be called and you are currently trying to call a server-side event instead. When defining such an event on an actual ASP.NET Button control, you instead want to use the OnClientClick event instead. But this doesn't really matter as you want to target a server-side event and not a client-side one.
Build Your Button Server-side
What you'll likely want to do is create an actual Button control, define a click event handler that points to your method, and then add that control to the page as opposed to building a string:
// Build your button with its specific properties
Button button = new Button();
button.ID = "Bttn_PDF";
button.CssClass = "btn btn-warning btn-xs";
// Wire up its click event
button.Click += bttn_Click;
// Add it to the form
PlaceHolder1.Controls.Add(button);

If I cannot use C# to respond in realtime to radio button CheckedChanged events in Sharepoint, how can I add client-side (jQuery) code to do it?

I posed a similar question about this before, and it would seem based on the answers that I received that I can't expect to be able to rely on a radio button's CheckedChanged event to fire in real time.
Am I really stuck with waiting until the form is submitted before that event fires, or can I add client-side (jQuery) code to handle it? If so, how? How can I mix jQuery client code in with my C# server code in a Sharepoint (2010) project?
What I want to be able to do now is to dynamically alter the controls on the page based on decisions made by the user (if they select this radio button, a particular textbox has this set of properties applied, and if the other radio button, a different set of properties). Is this possible?
UPDATE
I create controls and add CheckedChanged events to them like so:
rbUSCitizenOrPermResY = new RadioButton
{
CssClass = "finaff-webform-field-input"//,
//CheckedChanged += new EventHandler(rbUSCitizenOrPermResY_Changed) <= the name 'CheckedChanged' does not exist in the current context
};
rbUSCitizenOrPermResY.CheckedChanged += new EventHandler(rbUSCitizenOrPermResY_Changed);
cellRadioButton1_1.Controls.Add(rbUSCitizenOrPermResY);
The Save button is like so:
Button btnSave = new Button();
btnSave.Text = "Save";
btnSave.Click += new EventHandler(btnSave_Click);
this.Controls.Add(btnSave);
. . .
private void btnSave_Click(object sender, EventArgs e)
{
LiteralControl message = null;
try
{
message = new LiteralControl();
Controls.Add(message);
ConditionallyCreateList();
SaveInputToList();
List<ListColumns> listOfListItems = ReadFromList();
GeneratePDF(listOfListItems);
message.Text = "Saving the data and converting it to a PDF has been successful";
}
catch (Exception ex)
{
message.Text = String.Format("Exception occurred: {0}", ex.Message);
}
}
What is special about the Save button that it fires immediatley when clicked, yet the CheckedChanged event of a RadioButton does not fire (immediately)?
UPDATE 2
This says, "...UpdatePanel control ... by default, this control does not work with these standard SharePoint components..."
So it sounds like using it is trying to shoehorn a lumberjack's foot into a baby booty.
Then what is the preferred method for getting Sharepoint components to update?
UPDATE 3
Theoretically, it seems maybe this will work:
UpdatePanel up = new UpdatePanel();
up.Controls.Add(dynamicTable); // or just add the radio buttons, rather than the entire HtmlTable?
ScriptManager sm = new ScriptManager();
sm.EnablePartialRendering = true;
...I'll find out, I reckon...

Command event not firing asp.net for dynamically created control

I've got the following code that creates an image button dynamically on a li html tag. When I click the image button it does not fire the event. What am I doing wrong please?
Code that generates the control:
ImageButton cmdEdit = new ImageButton();
cmdEdit.ImageUrl = "~/Images/phone_book_edit.png";
cmdEdit.ID = "cmdEdit" + recordcount.ToString();
cmdEdit.Attributes["class"] = "liQuestionsLabel2";
cmdEdit.Width = 30;
cmdEdit.CommandName = "Edit";
cmdEdit.CommandArgument = (recordcount - 1).ToString();
cmdEdit.Command += new CommandEventHandler(EditQuestion_Command);
li.Controls.Add(cmdEdit);
Event code:
protected void EditQuestion_Command(object sender, CommandEventArgs e)
{
Response.Write("here");
}
Dynamically generated controls lose their state after they are rendered. For you to access them again once you postback, you will have to recreate them in the code-behind along with recreating the attached events as well.
Put the above code in your Page_Load but not inside the if(!IsPostback) so that it gets recreated and you can then access its event.
Other than that, the above code works fine for me when I recreated the same control in my page.

Dynamically created content is updating "a step behind" on button click

So I am creating a simple question/answer format and having an issue when submitting an answer. I dynamically create divs/buttons/textboxs from the database via a "RenderQuestions()" function. This creates a list of questions and answer textbox/buttons. When attempting to answer a question, I type my answer click submit and nothing happens. I do it again and it shows my first answer. It's a "step behind".. If I refresh it then shows all answers as it should. I've been struggling with this all night. Here's some code:
-----My page load----- (Relevant parts)
protected void Page_Load(object sender, EventArgs e)
{
//If authenticated hide login & show welcome bloc
if (User.Identity.IsAuthenticated)
{
//Show question & render
questionsBloc.Visible = true;
//if(Page.IsPostBack)
RenderQuestions();
}
-----RenderQuestions() function---- (The relevant parts)
//Initialize & get answers
List<Answer> answers = new List<Answer>();
answers = um.GetAnswers(q.QuestionID);
//Initialize html render
HtmlGenericControl questionDiv = new HtmlGenericControl("div");
TextBox txtAnswer = new TextBox();
Button btnAnswer = new Button();
//Set Answer Button
btnAnswer.Text = "Answer";
btnAnswer.Click += new EventHandler(btnAnswer_Click);
//Set ID's
btnAnswer.ID = "btnAnswer" + q.QuestionID.ToString();
questionDiv.ID = "questionDiv" + q.QuestionID.ToString();
//Set classes
questionDiv.Attributes.Add("class", "questionBloc");
btnAnswer.CausesValidation = false;
btnAnswer.EnableViewState = false;
//btnAnswer.UseSubmitBehavior = true;
//Fill inner text with question
questionDiv.InnerText = q.QuestionContent; //Insert question..
//actionDiv.InnerText = "Like/Dislike/Comment/Flag"; //Insert answer..
//Add answer textbox and button to action div
actionDiv.Controls.Add(btnAnswer);
//Add question div to qaDiv
qaDiv.Controls.Add(questionDiv);
//Add action div to qaDiv
qaDiv.Controls.Add(actionDiv);
//Add all controls to feedbloc
feedBloc.Controls.Add(qaDiv);
-----My btnAnswer event handler -----
private void btnAnswer_Click(object sender, EventArgs e)
{
UserManager um = new UserManager();
um.PostAnswer("My first answer!");
//RenderGlobalFeed();
}
That's every reference to my button.. Should I be initializing the btn click event in my page_init? Any help is much appreciated.
Thanks guys
Set AutoPostBack=true on btnAnswer. It's not triggering the server to act on the button click.
If you want to get event btnAnswer_Click triggered , then you must render the same Content and assign the eventHandler in every pageload(ie; the page load after the client button click must render the button again and EventHandler must be assigned).
Asp.net won't trigger the event if it doesn't find the controls in the pageload. Remember, after clicking a button, the page load event triggers first and then only the Click_event will be triggered.
The RenderQuestions() must be called in the btnAnswer_Click Event too. This will avoid the a step back problem.
In this scenario I would recommend you to learn about ajax (using jQuery library) requests in asp.net (using WebMethods or webservices) to avoid these postbacks.

ASP.NET Button click redirect to new page

I have created a Button programmatically.
I now want to redirect to a new aspx page on the click of this Button, such that we will enter into one of the methods of the new page (like page_load(), etc.)
Is this possible?
Eg:
Button oButton = new Button;
oButton.Text = "NextPage";
// Redirect to "Redirect.aspx" on click
But I am not able to find an entry point in Redirect.aspx where I can do some changes to the UI components once we get redirected to "Redirect.aspx"
Regards,
Parag
You need to handle Click event of oButton.
Button oButton = new Button();
oButton.Text = "NextPage";
oButton.Click += (sa, ea) =>
{
Response.Redirect("Redirect.aspx");
};
You can use query string parameters and depending on the value of param call the appropriate method in Page_Load of Redirect.aspx
e.g.
Redirect.aspx?val=1
in Redirect.aspx
protected void Page_Load(...){
string var = Request.QueryString["val"];
if(var == "1")
some_method();
else
some_other_method();
}
You could also use the PostBackUrl property of the Button - this will post to the page specified, and if you need to access items from the previous page you can use the PreviousPage property:
Button oButton = new Button;
oButton.Text = "NextPage";
oButton.PostBackUrl = "Redirect.aspx";
Then in you wanted to get the value from, say, a TextBox on the previous page with an id of txtMyInput, you could do this (very simple example to give you an idea):
void Page_Load(object sender, EventArgs e)
{
string myInputText = ((TextBox)PreviousPage.FindControl("txtMyInput")).Text;
// Do something with/based on the value.
}
Just another example of how to accomplish what I think you're asking.
See Button.PostBackUrl Property for more info.

Categories