I am new to C# and ASP.NET. I have a jQuery yes/no dialog that calls serverside methods (code-behind) using postback.
I put the code together using some snippets I've found on the internet, but I don't fully understand how the code is working.
If I click "yes" in the jQuery dialog, then the server-side C# method DeleteConfirmedServerside is called.
However I don't understand why it works because in the rendered html code I don't see a reference to the server-side method.
I've read some articles about javascript postback... but still I don't understand why the following code works:
.aspx file
// jQuery code (Dialog with yes/no Buttons)
buttons: [
{
id: "Yes",
text: "Yes",
click: function ()
{
$("#btnDeleteConfirmedClientside").click();
}
},
....
<asp:Button ID="btnDeleteCanceledClientside" runat="server"
OnClick="DeleteCanceledServerside" Text="DeleteCanceled"
UseSubmitBehavior="false" style="display:none"/>
<asp:Button ID="btnDeleteConfirmedClientside" runat="server"
OnClick="DeleteConfirmedServerside" Text="DeleteConfirmed"
UseSubmitBehavior="false" style="display:none" />
<div id="myDialog" style="display: none" >
Do you want to delete this record?
</div>
Code-behind (server side)
protected void DeleteConfirmedServerside(object sender, EventArgs e)
{
// called by postback from clientside
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Delete confirmed (YES).')", true);
}
Rendered HTML client side:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
...
<input type="button" name="btnDeleteCanceledClientside" value="DeleteCanceled"
onclick="javascript:__doPostBack('btnDeleteCanceledClientside','')"
id="btnDeleteCanceledClientside" style="display:none" />
<input type="button" name="btnDeleteConfirmedClientside" value="DeleteConfirmed"
onclick="javascript:__doPostBack('btnDeleteConfirmedClientside','')"
id="btnDeleteConfirmedClientside" style="display:none" />
<div id="myDialog2" style="display: none" >
Do you want to delete this record?
</div>
If the user clicks "yes" in jQuery dialog, then btnDeleteConfirmedClientside is "clicked" and then __doPostBack('btnDeleteConfirmedClientside&...) is called (at least this is what I understand)
What I don't understand is this in the rendered html:
onclick="javascript:__doPostBack('btnDeleteConfirmedClientside','')
Why is __doPostBack using btnDeleteConfirmedClientside and not the server-side code-behind method DeleteConfirmedServerside?
DeleteConfirmedServerside is called - but how is this happening, since nowhere in the HTML I see a reference to serverside methods... so how is the C# code-behind method DeleteConfirmedServerside called ?
The __doPostBack javascript method makes a post back to the server, effectively requesting that your server side method be called.
The hanlding of this HTTP post request is handled behind the scenes and calls your server side method.
If you're new to asp.net, I recommend that you start by having a look at http://www.asp.net/mvc and use asp.net mvc rather than asp.net webforms which is what you're using. MVC is the latest and greatest and has many advantages over webforms.
Related
I am using ASP.NET for a web page in order to make some server calls that involve looking up user organization information. Based on that information, we need to either hide or display a div. In the header I have a C# function that definitely runs. I have tried the following lines to hide the div.
divID.Style.Add("display","none");
and
divID.Visible = false;
In the body, I am currently using an asp:Panel that runs at server and contains the id "divID". No matter what I do, I can't get the div to hide (without manually putting the styling in). I tried putting the scripts before and after the body, and it didn't make a difference. Any suggestions on the best way to do this would be appreciated.
EDIT:
Here is the C# initiating code.
<script runat="server" language="C#">
void getUserInfo(Object sender, EventArgs ev){
The rest of the C# code is irrelevant, but the relevant line shown above is definitely being run.
The HTML portion looks something like this.
<asp:Panel runat="server" id="divID" style="width:200px; height:130px; ">
<div style="text-align:center">Test Data</div>
</asp:Panel>
C# code is always compiled and run from the server-side, and so cannot impact the state of a page once rendered unless you use postbacks or callbacks. If you want to change the visible state of a control on the client-side, you will need to use Javascript on the client side (possibly triggered by a button click) to show and hide the control.
As an example, check out the solution at the link below.
https://forums.asp.net/t/1603211.aspx?Show+hide+div+on+button+click+without+postback
<script type="text/javascript">
function ToggleDiv(Flag) {
if (Flag == "first") {
document.getElementById('dvFirstDiv').style.display = 'block';
document.getElementById('dvSecondDiv').style.display = 'none';
}
else {
document.getElementById('dvFirstDiv').style.display = 'none';
document.getElementById('dvSecondDiv').style.display = 'block';
}
}
</script>
<asp:Button ID="btn" runat="server" Text="Show First Div"
OnClientClick="ToggleDiv('first');return false;" />
<asp:Button ID="Button1" runat="server" Text="Show Second Div"
OnClientClick="ToggleDiv('second');return false;" />
<br />
<div id="dvFirstDiv" style="display: none;">
First Div
</div>
<div id="dvSecondDiv" style="display: none;">
Second Div
</div>
In the header I have a C# function that definitely runs.
If you're talking about the HTML page header - no, it definitely not running. C# code is executed only server side.
Based on your post, I'm assuming we're talking WebForms here and yo have a script block in your aspx file. While this is fine, I recommend placing the server-side code into a code behind file.
So all you need to do is to add a handler for the PreRender phase of the page life cycle and place your logic for showing/hiding the div in there.
public void Page_Prerender(object sender, EventArgs e)
{
divID.Visible = false;
' OR
'divID.Style.Add("display","none");
}
Note that setting the Visible property of a WebForms control excludes the control from rendering to the page, whilst setting display: none renders it as HTML but it isn't displayed on the page.
Try in backcode: divID.Controls.clear();
This worked for me.
I have the following code:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandle);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandle);
function beginRequestHandle(sender, Args) {
//Do something when call begins.
document.getElementById("btn1").style.visibility = "hidden";
document.getElementById("btn2").style.visibility = "hidden";
}
function endRequestHandle(sender, Args) {
if (document.getElementById('<%= hfResultsCount.ClientID %>').value != 0) {
document.getElementById("btn1").style.visibility = "visible";
document.getElementById("btn2").style.visibility = "visible";
}
else {
document.getElementById("results").innerHTML = "<br><b><center><font style='font-family:Haettenschweiler; font-size:xx-large'>No data found, please try again.</b></font></center>";
}
}
</script>
and the code for btn2:
<input type="button" runat="server" name="btn2" id="btn2" value="New Window"
style="visibility:hidden;font-weight:bold;width:200" onclick="window.open('http://microsoft.com');" />
I am using Js to show/hide buttons (needs to be done like this so don't suggest otherwise) and while btn1 is asp:button it always works but for <input type=button> I keep getting this error
Microsoft JScript runtime error: Unable to get value of the property 'style': object is null or undefined
The way to fix that for btn1 was to just add ClientID=Static but how to do that for <input> button? (I do not want to make it asp:button since I need it to not postback)
Everything is in an UpdatePanel with ClientID=Static also.
I know its something to do with the IDs and the master page since it works fine on a page on its own.
If you do not need to access button on server side then you should not put runat="server", This will make your script to find button and it will not generate error.
<input type="button" name="btn2" id="btn2" value="New Window"
style="visibility:hidden;font-weight:bold;width:200" onclick="window.open('http://microsoft.com');" />
OR, If you want to make runat="server" you can access it like this
document.getElementById(<%= btn1.ClientID %>).style.visibility = "visible";
After the page rendering go to view source and check how ID is appearing with master page you may get some idea
It might not be btn directly....master_xxx
This should work :
<input type="button" runat="server" ClientIDMode="Static"
name="btn2" id="btn2" value="New Window"
style="visibility:hidden;font-weight:bold;width:200"
onclick="window.open('http://microsoft.com');"/>
or, if you don't need to access the control in your code behind :
<input type="button" name="btn2" id="btn2" value="New Window"
style="visibility:hidden;font-weight:bold;width:200"
onclick="window.open('http://microsoft.com');"/>
To make sure that an event handler is written properly, I generally have Visual Studio generate the event for me. However, I can't find a way to do this with a div and I've tried typing it out myself to no avail. Is this even possible without writing any javascript? (I saw similar questions, but couldn't seem to find anything that fit my needs).
Edit: Basically I have a logoff div disguised to the user as a button. When they click it, I want the following to happen:
protected void LogOff_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Session.Abandon();
//This will clear the authentication cookie
HttpCookie myHttpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
myHttpCookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(myHttpCookie);
//This will clear the session cookie (not required for my application but applying to be safe)
HttpCookie myHttpCookie2 = new HttpCookie("ASP.NET_SessionId", "");
myHttpCookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(myHttpCookie2);
FormsAuthentication.RedirectToLoginPage();
}
Here's where I call this event:
<span class="MenuItem" runat="server" onclick="LogOff_Click">Log Off</span>
Your LogOff_Click is fine. However, you need to modify your markup. Apply the onserverclick event to the <a> tag instead of <span>. In your case, try the following:
<span class="MenuItem">Log Off</span>
Description
The div element supports the javascript event onclick so you can do it.
You can check if a html element supports a given event by looking on w3c shools tag definition.
It is not clear to me what you exactly mean. You can do many things using javascript on the client side. onclick is javascript but you can do things like redirects using the serverside (Postback on ASP.NET Webforms) too. Things you do with javascript are, without doing ajax, not noticeable by the server, cause javascript get handled by the browser.
Check out my sample and this jsFiddle Demonstration
Sample for the <div> tag
Html
<div onclick="alert('hello');">hello world</div>
More Information
jsFiddle Demonstration
w3c shools tag definition
If you wanted to stay in ASP.NET, you could use a Panel control and do something like this:
Markup
<body>
<form id="form1" runat="server">
<div>
<asp:Panel runat="server" ID="pan1">click here</asp:Panel>
</div>
</form>
</body>
Code Behind
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
pan1.Attributes.Add("onclick", "javascript:alert('here');return false;");
}
}
You're still writing JavaScript, but you're staying with the ASP.NET controls and the ASP.NET way of setting client-side events.
I actually prefer the method of dknaack and Silvertiger -- put the event in the client side code (preferably a javascript file instead of inline).
Standard DOM and CSS will allow this
<div style="cursor:hand;" onclick="this.document.location.href ='http://www.google.com';">
My content
</div>
should do the trick
Not sure what exactly you intend to do. When the onclick event is triggered, you would need a handler to be called, when the event is triggered. This is done via Javascript.
You can do a form submit in the JavaScript, or trigger an Ajax callback in the Javascript, to interact with your .NET application.
Answering the original question, onclick event can be triggered via <div> tag. Make sure you test against Internet Explorer 7/8 (compatibility mode) as not all events work in IE 7/8. It should be okay in Firefox, Chrome and IE9. Save this in a file and experiment.
<html>
<head>
<script type="text/javascript">
function JSFn()
{
//you can use the div ID if needed: var id = document.getElementById('div_id');
alert("JSFn was called");
//Can do form submit or Ajax callback to interact with .NET app
}
</script>
</head>
<body>
<div>
<a id="anchor1" href="javascript:JSFn();">Make a clickable link here, you can use onclick and href='#' </a>
</div>
<div id="div_id2" onclick="JSFn()">Just click here </div>
</body>
</html>
I am having some very strange behaviour in IE with my .Net buttons.
I have a normal HTML button.
<input type="submit" onclick="return Valadation()" value="Save profile" class="btn primary rounded" />
Which then calls some simple JavaScript
if (txbEmail.length == 0) {
$("[id$='txbEmail']").addClass("error");
$("[id$='txbEmail']").focus().select();
showMessage = true;
displayMessage += "Email Address, "
}
else {
$("[id$='txbEmail']").removeClass("error");
}
if (showMessage) {ShowStatus("warning", displayMessage);
return false;
}
else {
var saveButton = $('[id*="butSave"]');
saveButton.focus();
saveButton.click();
}
With the final result clicking a asp.net button
<asp:Button ID="butSave" runat="server" Style="display: none;" onclick="butSave_Click" />
This issue is that Ie just wont ever post the page back? works fine on FF, Chrome, just not IE
If you need the ASP button to perform javascript validation, use the OnClientClick property:
<asp:Button ID="butSave" runat="server" Style="display: none;" onclientclick="return Valadation()" onclick="butSave_Click" />
Simply return false from your Valadation() method to stop the asp button from submitting.
Turns out this is a known issues within jQuery and wont be fixed, but there is a very easy work around.
The script .click() will not work if the button in question has the type="submit" (only in IE wont this work IE7,IE8,IE9 all show this error).
But if you just change the button type to type="button" the .click() event works just fine.
I want to call a c# function from my javascript function.
I have a link button in my ascx (please see the code below). The problem is that if you press enter in firefox is not working however it is working fine in internet explorer.
<li class="clearfix border_top">
<label for="title" class="first_column bold">Search For</label>
<div class="contactUs_details">
<input type="text" id="advanced_txtBox1" name="advanced_txtBox1" class="searchbox" runat="server" style="width:300px;" />
<asp:CheckBox ID="chkSearchBDJ" runat="server" Text="Search BDJ" CssClass="checkboxlistnoborder" />
</div>
</li>
<div class="img_SearchNow">
<asp:LinkButton ID="btnSearchNow" CausesValidation="true" runat="server" OnClick="btnSearchNow_Click"></asp:LinkButton>
</div>
I have linkButton see above on which I have called on c# function on Click, But if you pree some text in above textbox and press "Enter" it should automatically call function "btnSearchNow_Click". It is working fine in IE but not working in Firefox.
A javascript function to click a button...
function clickMyButton() {
var ele = document.getElementById('btnSearchNow');
if ((ele !== null) && (ele != 'undefined')) {
ele.click();
}
}
The wording of your question could use some cleaning up, or some additional information.
If you are looking for pseudo-submit behavior from inside a text box, take a look at this post. Submit Login control button when I hit Enter
You will have to generate the javascript from the server side, since you are using an ASCX and the ID's are not the ones you defined.
You need to have a submit type on the page for it to work properly in firefox.
<input id="mysubmit" runat="server" type="submit" onclick="return false;" style="display: none;" />
Edit: Here's a google cached page that has more information. The original post doesn't seem to be available ATM, but good old google had it.