This is my C# building the html. I tried to change the OnServerClick with the onclick and onclientclick with the result that:
Onserverclick does not fire anything
onclick gives me an exception
that tells me that the method is not defined
onclientclick does not
fire nothing
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/img/"));
List<ListItem> files = new List<ListItem>();
tabellaDownload.InnerHtml += "<table>";
foreach (string filePath in filePaths)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
// tabellaDownload.InnerHtml += "<tr><td OnServerClick = 'DownloadFile' runat='server'>" + Path.GetFileName(filePath) + "<td></tr>";
tabellaDownload.InnerHtml += "<input type='button' runat='server' OnServerClick='DownloadFile' value='asd' />";
}
tabellaDownload.InnerHtml += "</table>";
string asd = "";
}
}
protected void DownloadFile(object sender, EventArgs e)
{
//do something
}
What are you trying to do is to add a control to your form so if you want to do it dynamically you need to do something like this:
protected void Page_Load(object sender, EventArgs e)
{
HtmlButton b = new HtmlButton
b.ServerClick += MyEvent;
tabellaDownload.Controls.Add(b);
/* a table control doesn't accept a btn as child, you need to the exact td cell where insert the button*/
}
protected void MyEvent(object sender, EventArgs e)
{
}
Everything in web form is a control included in a controls collection.
The Aspx files contains in forms of mark-up a mix of html and server directives(you can notice the difference by the runat attribute which marks the server directives), the server side directives are rendered as html mark-up to send to the browser, in a way similar to this:
<input name="ctl00$MainContent$ctl00" onclick="__doPostBack('ctl00$MainContent$ctl00','')" type="button">
When you assign a string to InnerHtml attribute of a control, you are sending exactly what you want to render client side but there is no one html specific(or ecma script specific) that defines the runat attribute!
Related
In my javascript file, I got an ajax to get all list and iterate these data and append <a id='userID' class='btn'>Assign ID<> to my list.
So, how do a add postback to these anchor and redirect it inside my method in the server. Below is my code but didn't work. When I click the achor button, it just redirect/refresh to the same page without doing any changes and didn't show the text.
<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick='javascript:__doPostBack('uniqueID','')'>Assign ID</a>
protected void Action_assignID(object sender, EventArgs e)
{
// assign ID action
Response.Write("Pass");
}
You should be changed your button to:
<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick="javascript:__doPostBack('uniqueID','Assign ID')">Assign ID</a>
And it's a good idea to implement the IPostBackEventHandler interface in your codebehind as below:
public partial class WebForm : Page, IPostBackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
}
}
public void RaisePostBackEvent(string eventArgument)
{
// do somethings at here
}
}
Hope this help!
The __doPostBack method really doesn't do anything special except, well... perform a POST operation back to the same page with two specific form arguments.
The first parameter is the __EVENTTARGET and the second parameter is the __EVENTARGUMENT.
The magic all happens in ASP.Net where it automagically wires up your controls to event handlers, but since you are creating these entirely in JavaScript the server doesn't know that those controls exist.
However, you can manually grab these values and do something with them.
//Client Side JavaScript:
__doPostBack('my-event', '42');
//Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
var target = Request.Params["__EVENTTARGET"];
var args = Request.Params["__EVENTARGUMENT"];
Target.Text = target; // 'my-event'
Argument.Text = args; // '42'
}
}
In my Sharepoint 2010 app, I'm handling most events client-side with jQuery. However, for the saving of data to the Sharepoint list, and the generation of a PDF file with that data, I want to handle that server-side, with C#.
I tried to invoke a C# event this way:
0) Aded an HTML button in my project's *.ascx file:
<button type="button" name="saveData" id="saveData">Save Data</button>
1) Added jQuery to respond to that button being clicked (in the same *.ascx file):
$("#saveData").click(function () {
$('#hiddenSave').trigger('valuechanged');
});
2) Created a hidden element in the server-side C# (in the *.ascx.cs file):
HiddenField hiddenSave = null;
protected void Page_Load(object sender, EventArgs e)
{
base.OnPreRender(e);
hiddenSave = new HiddenField();
hiddenSave.ID = "hiddenSave";
hiddenSave.ValueChanged += new EventHandler(hiddenSave_ValueChanged);
this.Controls.Add(hiddenSave);
}
protected void hiddenSave_ValueChanged(object sender, EventArgs e)
{
GeneratePDF();
}
private void GeneratePDF()
{
;//bla
}
But I never reach the "ValueChanged" event handler; $("#saveData").click() fires, but not hiddenSave_ValueChanged().
So do I need a tweak to this, or a completely different approach? How can I do as much as possible client-side with jQuery, but also run server-side/C# code where necessary, in a Sharepoint 2010 app?
UPDATE
A little more detail, and about additional things I've tried: I'm creating a button on a Sharepoint page dynamically (in C#) in my *.ascx.cs file:
Button btnSave = null;
protected void Page_Load(object sender, EventArgs e)
{
base.OnPreRender(e);
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save the Data";
btnSave.Click += new EventHandler(btnSave_Click);
btnSave.Visible = false;
this.Controls.Add(btnSave);
}
protected void btnSave_Click(object sender, EventArgs e)
{
btnSave.Text = "You clicked me!";
PostTravelData ptd = new PostTravelData();
}
I set it visible at the right time in the client-side jQuery in the *.ascx file:
$('#btnSave').show();
However, clicking the button does not reach the btnSave_Click() event - the breakpoint there is never reached, nor is the button's text changed. Why not?
Even when I don't set the button invisible (comment out the "btnSave.Visible = false;" line), the click handler isn't reached...is Page_Load() too late? Is there an earlier page event I can use that would work?
I tried moving it from Page_Load() to OnPreRender(), too, like this:
protected void OnPreRender(EventArgs e)
{
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save the Data";
btnSave.Click += new EventHandler(btnSave_Click);
//btnSave.Visible = false;
this.Controls.Add(btnSave);
}
...(and OnRender()) but the button doesn't even display...
And, trying a different tack, I commented out the dynamic creation server-side code and tried to attach to a button created in the HTML (*.ascx file):
<button type="button" name="saveData" id="saveData" runat="server" onclick="saveData_Click">Save Data</button>
(by adding the "runat server" and the onclick handler), and then adding this "code-behind" (*.ascx.cs)):
protected void saveData_Click(object sender, EventArgs e)
{
PostTravelData ptd = new PostTravelData();
SaveToList(ptd);
GeneratePDF(ptd);
}
...but there was still no joy in Mudville -- the breakpoint in the handler is not reached.
Yet another attempt was:
In the *.ascx:
<asp:Button runat="server" id="saveData" name="saveData" onclick="saveData_Click" Text="Bla" />
In the code-behind:
saveData.Click += saveData_Click;
The "Bla" button is created, but clicking on it reaches not the breakpoint in the "saveData_Click" handler.
I even adapted some code from here like so:
Button btnSave = null;
. . .
protected override void CreateChildControls()
{
btnSave = new Button();
btnSave.Width = new Unit(150, UnitType.Pixel);
btnSave.Text = "Can you see me?";
btnSave.Click += new EventHandler(btnSave_Click);
Controls.Add(btnSave);
}
...but I still do not reach the "protected void btnSave_Click(object sender, EventArgs e)" handler when I click the button.
Surely there's a way to get a handle on the button server-side and manipulate it (specifically, respond to its click event)...?!?
First of all, as far as I know, there is no such event for input type hidden in a ascx page. If you create the input type hidden with runat server in the ascx code then you'll see that when you try to add this event it's not available. However there are other events like OnClick that you can simulate to get the desired result.
I have RegisterClientScriptBlock which is written inside page load of .aspx file protected void Page_Load(object sender, EventArgs e)
The Script actually gets ID From URL and then Pass it to openticketPageLoad() function of javascript.
But it is not getting into openticketPageLoad() function. But .aspx page is loading.
openTickets.aspx.cs
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "openTicketsScript", "<script type=\'type/javascript\'>$(document).ready(function(){openticketPageLoad(" + Request.QueryString["ID"].ToString() + ");});</script>".ToString(), true);
}
}
Inside my javascript file
function openticketPageLoad(b)
{
alert(b); //No alert window coming.
}
See the documentation here: http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerclientscriptblock.aspx
The last parameter is a boolean that specifies whether ASP.net should generate Script tags. As you already specify them I expect if you look at your source you are generating nested script tags.
Can you try the following code:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(),
"openTicketsScript", string.Format("openticketPageLoad({0});", Request.QueryString["ID"]), true);
}
}
Try this
Page.ClientScript.RegisterStartupScript(this.GetType(), "openTicketsScript", "<script type=\'type/javascript\'>$(document).ready(function(){openticketPageLoad(" + Request.QueryString["ID"].ToString() + ");});</script>".ToString(), true);
Perhaps you could do is assign the call to your javascript function direct in the load event of the body of the page. To assign the load function of the body from a content page can do the following:
HtmlGenericControl body = this.Master.FindControl("body") as HtmlGenericControl;
body.Attributes.Add("onLoad", "openticketPageLoad(" + Request.QueryString["ID"].ToString() + ");");
And in the master page add the runat="server" to the body element:
<body id="body" runat="server">
I hope this helps.
I have a table with all the objects I have in my db. I load them in my Page_Load function. I have a text field and a button that when clicking the button, I want the handler of that click to put a new object with the name written in the text field in the db.
Now, I want that what happens after the click is that the page loads again with the new item in the table. The problem is that the button event handler is run after the Page_Load function.
A solution to this would be to use IsPostBack in the Page_Load or use the pre load function. A problem is that if I would have 3 different buttons, I would have to differ between them there instead of having 3 different convenient functions.
Any solutions that don't have this problem?
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
// LOAD DATA FROM DB
}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
}
Maybe you should try loading your data during PreRender instead of Load
protected void Page_Load(object sender, EventArgs e)
{
this.PreRender += Page_PreRender
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
}
protected bool reloadNeeded {get; set;}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
reloadNeeded = true;
}
protected void Page_PreRender(object sender, EventArgs e)
{
if(reloadNeeded || !IsPostBack)
// LOAD DATA FROM DB
}
You can check the event target and do what you need then:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string eventTarget = Page.Request.Params["__EVENTTARGET"];
if(whatever)
{
//do your logic here
}
}
}
Get control name in Page_Load event which make the post back
Use the Page_PreRenderComplete event to retrieve your table. That way your page will always have the most recent data available after all user events have fired.
Why don't you move what you have in the click event into a new method. Then call that method as the first line in your page load?
An old question but I faced the same problem in my C#/ASP.NET Website with master/content pages: a click on a link on the master page should change a query parameter for a gridview on the content page. As you stated the button click event is handled after Page_Load. But it is handled before Page_LoadComplete (see the information about ASP.NET Page Life Cycle), so you can change the page content there.
In my case I solved the problem by setting a session variable in the click event in the master page, getting this variable in the Page_LoadComplete event in the content page and doing databind based on that.
Master page:
<asp:LinkButton ID="Btn1" runat="server" OnCommand="LinkCommand" CommandArgument="1" >Action 1</asp:LinkButton>
<asp:LinkButton ID="Btn2" runat="server" OnCommand="LinkCommand" CommandArgument="2" >Action 2</asp:LinkButton>
protected void LinkCommand(object sender, CommandEventArgs e)
{
HttpContext.Current.Session["BindInfo", e.CommandArgument.ToString());
}
Content page:
protected void Page_LoadComplete(object sender, EventArgs e)
{
string BindInfo = HttpContext.Current.Session["BindInfo"].ToString();
YourBindDataFunction(BindInfo);
}
How to display a messagebox from the ASP.net(C#) master page itself. I mean when a link button on the master page is clicked a message box is to be displayed. i've tried calling the following method with no result.
public void MessageBox(string message, Page page)
{
if (!string.IsNullOrEmpty(message))
{
Label lbl = new Label();
lbl.Text = "<script type=\"text/javascript\" language=\"javascript\">"
+ "alert('" + message + "'); " + "</script>";
page.Controls.Add(lbl);
}
}
Either register the OnClientClick to the LinkButton, then the alert will be shown before the postback, or register the alert-script in the Click-Event handler during postback, so that the alert will be shown as soon as the page is rendered to the client the next time:
protected void Page_Load(object sender, System.EventArgs e)
{
MyButton.OnClientClick = "alert('MyButton clicked!');";
}
protected void MyButton_Click(object sender, System.EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "AlertScript", "alert('MyButton clicked!');", true);
}
I just put your code into a page and it worked with no problem. It was not a master page but I see no difference in why it wouldn't work in a master page just as well. Here is the code that worked for me:
The linkbutton in the page:
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
The code behind:
public void MessageBox(string message, Page page)
{
if (!string.IsNullOrEmpty(message))
{
Label lbl = new Label();
lbl.Text = "<script type=\"text/javascript\" language=\"javascript\">" + "alert('" + message + "'); " + "</script>";
page.Controls.Add(lbl);
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
MessageBox("test", Page);
}
You should use ClientScriptManager.RegisterClientScriptBlock to add scripts to the page instead of literal controls with javascript values.
I'd suggest a base class for your master page, something like:
public sealed class MasterPageBase : MasterPage
{
protected void AddAlertMessage(string Message)
{
var script = String.Format("alert('{0}');", Message);
this.Page.ClientScript
.RegisterStartupScript(this.GetType(),"PageAlertMessage",script,true);
}
}
Now set this as your base across your master pages, and you can call:
protected void LinkButton1_Click(object sender, EventArgs e)
{
this.AddAlertMessage("Hello");
}
The main benifit is that the script details are abstracted away, and you can easily make global changes to them (switching to a Growl Style alert for instance) without making many page edits.
On the page load of master page write the following code
lnkButton.Attributes.Add("onclick","alert('message');");
The following code worked for me.
linkbutton1.OnClientClick ="javascript:alert('Hello')"