I'm developing a C# ASP.NET application under VS2010. I want to generate a dynamic table by writing HTML text into a literal, including dynamically inserted buttons on my table. I know how to create dynamic ASP.NET controls, but I have a small problem with dynamic HTML controls. I've created an HTML button but I don't know how to give it a server-side click function.
Can I create dynamic ASP.NET controls and insert them in my literal? How can I get a dynamically created button to trigger a server-side event?
I've used OnServerClick property for defining my server side function but it has no effect, how can I use this value?
If you want post back on your button click, you will have to add __doPostBack function on it's onclick event, for this you can add a button like
StringBuilder dynamicHtml = new StringBuilder();
dynamicHtml.Append("Your Html Code");
dynamicHtml.Append("<input type='button' id='btn1' name='btn1' onclick='__doPostBack(\'btn1\',\'\')' value='Click Here' />");
when you click on it, it will post back, and you can check Request.Form["__EVENTTARGET"] to find who post back the page.
By checking Request.Form["__EVENTTARGET"] in Page_Load event handler, you can call your any server side method like
protected void Page_Load(object sender, EventArgs e)
{
var eventTarget = Request.Form["__EVENTTARGET"].ToString();
if(eventTarget == "btn1")
{
CallMethod1();
}
}
private void CallMethod1()
{
//Code which you want to run
}
Related
I am using a jQuery editor and when the user hits the submit button i put the content into asp.net Panel control as html and then when i render this Panel the html i added is not
retrieved.
function MoveData() {
var sHTML = $('#summernote_1').code();
// dvFrontPageHtml is asp.net Panel
$('[id*=dvFrontPageHtml]').html(sHTML);
setTimeout(function () {
javascript: __doPostBack('ctl00$ctl00$ContentPlaceHolderBody$ContentPlaceHolderBody$lnkSave', '');
}, 10000);
return false;
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
dvFrontPageHtml.RenderControl(htmlWriter);
string Message = sb.ToString();
The message does not returning the html added.
I dont want to use jQuery ajax call as of now.
Any suggestions
without seeing all the relevant code its hard to pinpoint the problem.
but im pretty sure you are trying to find an ASP.net control by its serverside ID from clientside.
dvFrontPageHtml is the Controls ID by which asp.net identifies it, and unless you explicitly tell ASP.Net otherwise, it will generate a different ID for the control to be used by scripts at clientside
you need to retrieve the panel's clientside ID thats being generated for it by asp.net
you do it by a preprocessor directive <%=dvFrontPageHtml.ClientID%>:
$('[id*=<%=dvFrontPageHtml.ClientID%>]').html(sHTML);
alternatively, if you want the clientside ID to be same as the serverside ID, you can set the control's attribute ClientIDMode="Static".
UPDATE:
from your comment it seems the problem is elsewhere. what comes to mind, is that RenderControl() takes the control as it was when sent to the client in the Response. but the control is not being submitted to the server in next Request, so you will not be able to retrieve its altered html.
what you can do as a workaround, is hook into ASP.NET's build in postback mechanism, and submit the panel's html as a custom event argument:
for the example, lets assume this is our html:
<asp:Panel ID="dvFrontPageHtml" runat="server" ClientIDMode="Static">test</asp:Panel>
<asp:Button ID="BT_Test" runat="server" Text="Button"></asp:Button>
this will be our javascript:
$(function(){
// add custom event handler for the submit button
$("#<%=BT_Test.ClientID%>").click(function (ev) {
//prevent the default behavior and stop it from submitting the form
ev.preventDefault();
//alter the panels html as you require
var sHTML = $('#summernote_1').code();
$('[id*=dvFrontPageHtml]').html(sHTML);
//cause a postback manually, with target = BTCLICK and argument = panel's html
__doPostBack('BTCLICK', $('[id*=dvFrontPageHtml]').outerHTML());
});
});
and here we capture the postback on serverside:
//we monitor page load
protected void Page_Load(object sender, EventArgs e)
{
string Message;
//check if its a postback
if (IsPostBack)
{
//monitor for our custom target "BTCLICK"
if (Request.Form["__EVENTTARGET"].CompareTo("BTCLICK") == 0)
{
// retrieve the panels html from the event argument
Message = Request.Form["__EVENTARGUMENT"];
}
}
}
I have a HTML webform (NOT asp.net webform) that submits its form to an aspx script.
On the aspx script, I'd like to simply forward the form submission to a different form processing script. (after checking just one or two things using Request.Form["variable"])
What is the simplest way to forward the original html page's form submission?
Currently:
html1 -> aspx1 -> html2
Desired:
html1 -> aspx1 -> aspx2 -> html2
I would attempt to solve this problem in the following fashion
Create a Repeater
Set the Request.Form as the datasource of the repeater. If this does not work, i would convert Request.Form into a suitable datastructure, such as a Dictionary or Datatable for binding to the Repeater
Each repeater item would have an input tag, and would receive the appropriate name/id and value. I would not use a server-control input tag. I would emit the string in a more organic fashion.
I would then post to the second aspx page.
The purpose of the repeater is to build an equivalent Form NameValueCollection for processing on the second aspx page.
References
Cross Page Postback
Posting to another page
Binding a Dictionary to a Repeater
Binding Dictionary to DropDownList - (Note, "Key", "Value")
If it is only about simplest way then it is using session variable.
Just save your form values to the session and then you can access it anywhere in your application during the particular session.
So I would have my aspx1 page something like this
// ASPX1 page's Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["variable"] == "SomeValue")//some condition
{
// save these values to session so that they will
// be available when I will be in aspx2 page
Session["FormValues"] = Request.Form;
Response.Redirect("ASPX2.aspx"); // your aspx2 page's link
}
}
And aspx2 page something like this
// ASPX2 page's Page_Load
protected void Page_Load(object sender, EventArgs e)
{
// form values from aspx1 page
NameValueCollection formValuesCollection =
(NameValueCollection)Session["FormValues"];
string variableValue = formValuesCollection["variable"];
// some processing using form values from aspx1 page
Response.Redirect("HTML2.html");
}
I am trying to fire a form submit via jQuery and have a particular server side event fire.
Client Side Code:
$("input[name=__EVENTARGUMENT]").val("SomeArg");
form = $("body form");
form.submit();
Server Side Code:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (Request["__EVENTARGUMENT"] == "SomeArg")
{
//do some stuff
}
}
}
The problem is, the "__EVENTARGUMENT" hidden input does not exist. I discovered that if I add an ASP.net server control dropdownlist with autopostback = true, the EVENTARGUMENT hidden input is created. Is there a cleaner way to have ASP.net create these hidden inputs, and allow me to get their values server side without adding controls I do not actually need on the page?
Add asp.net HiddenField control to the page
But you will have a problem which is to get this control id, which as.net generates automatically, you can solve this using the ClientID property for the hidden field like this article mentions
I have a gridview button that I programmatically created and I want to load an update panel on the client side with the sent data. I have a hidden value field that gets its data on the click of the gridview button and the dropdownlist in my updatepanel depends on that value.
while calling __doPostBack directly will work, it's not a perfect solution because the name of that function is strictly speaking an implementation detail of the .Net framework.
A better solution is to use ClientScriptManager.GetPostBackEventReference, which gives you a more resilient interface to the same functionality. Do note that GetPostBackEventReference and GetCallBackEventReference are not the same thing - the former causes a page reload (partial or full, depending on how your UpdatePanels are set up), while the latter doesn't.
The easiest way to do this is to call __doPostBack from client side.
On client side button1_onclick method, calls:
__doPostBack('<%=UpdatePanel1.ClientID %>','Refresh:0,1,2'); //refresh update panel
On page behind add the following event handler to capture the post back call:
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
string arg = Request.Form["__EVENTARGUMENT"];
if (string.IsNullOrEmpty(arg)) return;
if (arg.StartWith("Refresh")
{
//parse data first then do your thing here...
}
}
And of course don't forget to wire event to the above method:
protected void Page_Init(object sender, EventArgs e)
{
UpdatePanel1.Load += new EventHandler(UpdatePanel1_Load);
}
we use the __dopostback() method which simulates a postback and causes the updatepanel to refresh
__doPostBack('controlName','');
Don't forget that the control name is it's HTML ID (which may well contain dollars etc) and not just it's ASP.NET ID.
As far as I know you can either call this method and pass in the hidden value field, or the div that it is in.
I want to create a asp.net button control / link button control when user makes an ajax call to my server page (another asp.net page) and I wnt to do something on the button click event of this button. How to do this ? Do i need to use delegate ?
No, you don't need a delegate for this, it will be created for you. In your AJAX callback you should do something like this:
Button btn = new Button();
btn.Click += MyOnClickMethod; // must use +=, not =
btn.Text = "click me";
myUpdatePanel.Controls.Add(btn); // the AJAX UpdatePanel that you want to add it to
myUpdatePanel.Update(); // refresh the panel
The method MyOnClickMethod must have the same signature as a normal Click handler. Something like this will do:
protected void MyOnClickMethod(object sender, EventArgs e)
{
// do something
}
that's about it. There are many intricacies involved with dynamic controls, but the basis is as laid out above.