linkbutton with multiple link options - asp.net

I have two files for this year and next year, and the linkbutton has to point to the different file depends on the year. But the problem is we want to open the file in a new window. So I decide to call javascript from the server side
code for asp:linkbutton
<asp:LinkButton ID="guide" runat="server" Text="XXX" OnClick="guide_click">
javascript code
function Guidelink2013() {
window.open('XXX1.pdf', '', 'width=750,height=900'); return false;
}
function Guidelink2012() {
window.open('XXX2.pdf', '', 'width=750,height=900'); return false;
}
code behind
protected void guide_click(object sender, EventArgs e)
{
if (Session["YearLastLicence"] != null)
{
if (int.Parse(Session["YearLastLicence"].ToString()) < DateTime.Now.Year)
{
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:Guidelink2012();", true);
}
else ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:Guidelink2013();", true);
}
}
It works fine when first opening the page, but if I refresh the page, the pop up window will open automatically as well. Any idea? thanks

You should write the code in the page load and not in the click event of the link button.
So on page load,
if (Session["YearLastLicence"] != null)
{
if (int.Parse(Session["YearLastLicence"].ToString()) < DateTime.Now.Year)
{
guide.Attrbuites.Add("onclick","javascript:Guidelink2012();return false;");
}
else {
guide.Attrbuites.Add("onclick" "javascript:Guidelink2013();return false;");
}
}
You can also remove the click event from the Linkbutton.

Related

How to open multiple popup window's in ASP.NET on button click

I have struck in one doubt.
I am using one asp button. In this button click event I'm using if and else condition.
If block shows one popup and else block show another popup:
if (Session["id"] != null)
{
//one popup
}
else
{
//Second pop up Show
}
<asp:Button ID="btnAvailabilty" runat="server" class="btn btn-success" Text="Check Availability" OnClick="btnAvailabilty_Click" />
You need to write that in client side if you need to write a JavaScript code there,
if (Session["id"] != null) {
ClientScript.RegisterStartupScript(this.GetType(), "something",
"alert('Your message');",
true);
} else {
ClientScript.RegisterStartupScript(this.GetType(), "something",
"alert('Your other message');",
true);
}
You can also try to run the message variable to be changed, while leaving maximum of the code in one statement,
var message = "Your message";
if (Session["id"] == null) {
message = "Your other message";
}
ClientScript.RegisterStartupScript(this.GetType(), "something",
$"alert({message});", // Requires C# 6
true);
If you can write native JavaScript, such as Razor, then that will go like,
<script>
#if (Session["id"] != null) {
alert('Your message');
} else {
alert('Your other message');
}
</script>
Depends on your need.

Stopping onclick from firing when onclientclick is false?

Is it possible to use the onclientclick property of a button to do a clientside check. If the check returns true, then fire the onclick event. If the clientside check returns false, don't fire the onclick event.
Is that possible?
UPDATE:
These 2 work:
Stops the form from submitting:
OnClientClick="return false;"
Allows the form to submit:
OnClientClick="return true;"
The next 2 do not work:
// in js script tag
function mycheck() {
return false;
}
// in asp:button tag
OnClientClick="return mycheck();"
// in js script tag
function mycheck() {
return true;
}
// in asp:button tag
OnClientClick="return mycheck();"
It submits the form both times.
Why is that?
You want to add return inside OnClientClick after a function is called. Otherwise, the button will post back even if function returns false.
<asp:button ID="Button1" runat="server" OnClick="Button1_Click"
OnClientClick="return checkValidation()" Text="Submit" />
<script type="text/javascript">
function checkValidation() {
return confirm('Everything ok?');
}
</script>
Sure. If you use return false within your OnClientClick it will prevent any navigation from happening. So you're code would look like:
<asp:LinkButton runat="server" OnClientClick="if(!ValidatePage()) { return false;}" />
Yes you can, In onclientClick function call use preventDefault()
function onclientClickFun(e)
{
if(!IsValidationSuccess)
{
e.preventDefault();
}
}
OR
function onclientClickFun(e)
{
if(!IsValidationSuccess)
{
return false;
}
}
In the server page create the button:
var button1 = new Button();
button1.ServerClick += new EventHandler(button1_ServerClick);
button1.OnClientClick = SetJsForSaveBtn();
button1.Attributes.Add("UseSubmitBehavior", "false");
panel.Controls.Add(button1 );
//Contains the server code
private void saveBtn_ServerClick(object sender, EventArgs e)
{
//do something if ClientClick returns true
}
//Contains the JS code for the page
LiteralControl js = new LiteralControl();
panel.Controls.Add(js);
js.Text =#"<script type='text/javascript'>
$(document).ready(function(){
function CheckValidationOnClient(){
if(!ValidatePage()){
return false;
}
else{
return true;
}
};
});
</script> ";
private string SetJsForSaveBtn()
{
var jsfunc = #" return CheckValidationOnClient()";
return jsfunc ;
}
I came across this issue too. Did not like to have to put the OnClientClick=return false on every linkbutton. With a simple page it just easier to use an anchor and avoid asp filling the href in for you.
However this is not always possible. So a Simple conclusion is just to inherit the LinkButton and add a variable like AutoPostBack. if false then just override the output with the html or add the OnClientClick in. I dont really like inline tags.
namespace My.WebControls {
[ToolboxData("<{0}:LinkButton runat=server ID=btn></{0}:LinkButton>"), ParseChildren(true), ToolboxItem(true)]
public class LinkButton : System.Web.UI.WebControls.LinkButton {
private bool _postback = true;
[Bindable(true), Category("Behavior"), DefaultValue(true), Description("Gets or Sets the postback click behavior")]
public bool AutoPostBack { get { return _postback; } set { _postback = value; } }
protected override void Render(System.Web.UI.HtmlTextWriter writer) {
if(!AutoPostBack){
this.OnClientClick = "return false";
}
base.Render(writer);
}
}
}
Many attributes should need to be handled in a ViewState but in this case I think we are good;

JQuery Plugin: calling jConfirm from asp.net (code behind)

i am using jquery plugin and i got stuck in how to display the confirmation window from code behind and if the user choose "ok" than go ahead delete otherwise ignore.
jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
jAlert('Confirmed: ' + r, 'Confirmation Results');
});
anybody have done similar?
Why do you need to display this from the code behind? The user will initiate an action on the client, which is where this should be done.
If you're trying to put this on a delete button or something that's auto-generated:
$('.delButton').click(function(){
jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
jAlert('Confirmed: ' + r, 'Confirmation Results');
});
}
where .delButton is a class you could add to your delete buttons (or you can do whatever else you need to find which ones you attach this to). if you need you can also put the .live in there so jQuery will auto-hook up on new elements.
After the click, the inner jAlert can be removed and you can do your other logic inside.
it did not work with JConfirm i decided to go with JS
//Aspx:
<asp:LinkButton ID="LinkButton1" runat="server" Text="Click Me"
onclick="LinkButton1_Click" />
//JS
<script type="text/javascript">
function MyMethod()
{
if(confirm('Are you sure?'))
{
alert('Deleted');
return true;
}
else
{
alert('Not Deleted');
return false;
}
}
</script>
//Code Behind (C#)
protected void Page_Load(object sender, EventArgs e)
{
LinkButton1.Attributes.Add("onclick", "return MyMethod();");
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
}
The following code worked from a LinkButton un ASP.Net
$(".actionLink").click(function() {
var callFrom = $(this);
jConfirm("Are You Sure?",
'Please Confirm',
function(r) {
if (r) {
__doPostBack(callFrom.attr('id').replace(/_/g, '$'), '');
}
});
return false;
});

How to clear all form fields from code-behind?

HTML has an input button type to reset all fields in a form to their initial state in one step: <input type="reset" ... />.
Is there a similar simple way to reset all form fields of an aspx page from code-behind? Or is it necessary to reset all controls one by one with TextBox1.Text=string.Empty, TextBox2.Text=string.Empty, etc. ?
Thanks in advance!
Update:
Context is a simple Contact/"Send us a message" page with 8 asp:TextBoxes on the page (where the user enters the name, address, phone, email, message, etc.). Then he clicks on submit, the Onclick message handler in code-behind sends an email to some administrator, and all the form fields the user filled in should be emptied and he gets a notification in a label ("Message sent blabla..."). I want to have the form fields cleared to avoid that the user clicks again on submit and the same message is sent a second time.
You need only write a fork for each type of control unless one of the control has something special that needs to be done to reset it.
foreach( var control in this.Controls )
{
var textbox = control as TextBox;
if (textbox != null)
textbox.Text = string.Empty;
var dropDownList = control as DropDownList;
if (dropDownList != null)
dropDownList.SelectedIndex = 0;
...
}
ADDITION You asked how to clear controls even ones that are buried. To do that, you should create a recursive routine like so:
private void ClearControl( Control control )
{
var textbox = control as TextBox;
if (textbox != null)
textbox.Text = string.Empty;
var dropDownList = control as DropDownList;
if (dropDownList != null)
dropDownList.SelectedIndex = 0;
...
foreach( Control childControl in control.Controls )
{
ClearControl( childControl );
}
}
So, you would call this by passing the page:
ClearControls( this );
Refer this link for more information
http://www.freshcodehub.com/Article/3/clear-all-fields-like-textbox-dropdownlist-checkbox-radiobutton-label-after-form-submission-in-aspnet-c
public void ClearControls(Control parent)
{
foreach (Control c in parent.Controls)
{
if ((c.GetType() == typeof(TextBox))) //Clear TextBox
{
((TextBox)(c)).Text = "";
}
if ((c.GetType() == typeof(DropDownList))) //Clear DropDownList
{
((DropDownList)(c)).ClearSelection();
}
if ((c.GetType() == typeof(CheckBox))) //Clear CheckBox
{
((CheckBox)(c)).Checked = false;
}
if ((c.GetType() == typeof(CheckBoxList))) //Clear CheckBoxList
{
((CheckBoxList)(c)).ClearSelection();
}
if ((c.GetType() == typeof(RadioButton))) //Clear RadioButton
{
((RadioButton)(c)).Checked = false;
}
if ((c.GetType() == typeof(RadioButtonList))) //Clear RadioButtonList
{
((RadioButtonList)(c)).ClearSelection();
}
if ((c.GetType() == typeof(HiddenField))) //Clear HiddenField
{
((HiddenField)(c)).Value = "";
}
if ((c.GetType() == typeof(Label))) //Clear Label
{
((Label)(c)).Text = "";
}
if (c.HasControls())
{
ClearControls(c);
}
}
}
using the manual approach of String.Empty for each and every Textbox or any other field will be cumbersome, also by using Response.Redirect(); it will be difficult to show any confirmation message or same. So, on reading so many blogs i have found a reliable approach so far:
Public void reset(Control control)
{
foreach (Control x in control.Controls)
{
if (x is TextBox)
{
(x as TextBox).Text = String.Empty;
}
else if (x is DropDownList)
{
(x as DropDownList).SelectedIndex = 0;
}
.
.
reset(x);
}
}
use this code as reset(this); in your page wherever you want to reset or clear the values. At end of the if conditions do not forget to use the function recursively using the same
`Control` object x.
Using form.Controls.Clear() is not such a good approach because it will clear the entire form and you will even lose all the buttons on the form.
Instead if you just want to clear all the form fields like text fields and radio buttons I would recommend you try the following:
If you have a Reset button “Button1” then on click call a function reset();
In the reset function:
protected void resetButton_Click(object sender, EventArgs e)
{
TextBox1.Text=""; //set equal to empty string to all fields
}
Or redirect to same page by terminating the previous page
protected void resetButton_Click(object sender, EventArgs e)
{
Response.Redirect("~/Test2.aspx", true);
}
For your scenario the easiest way to clear the fields, in my opinion, is to turn off the ViewState (EnableViewState=false) of the controls you want to appear blank after the submit.
Or perhaps for the whole page unless there is some state you need.

ASP:TextBox Value disappears in postback only when password

I have an asp.net textbox like this:
<asp:TextBox ID="PINPad" runat="server" Columns="6" MaxLength="4"
CssClass="PINTextClass"></asp:TextBox>
It is, as you might have guessed, the text box from an on screen PIN pad. Javascript fills in the values. The page is posted back every five seconds (using an update panel if that matters) to update various other unrelated items on the screen. This works just fine.
However, when I convert it to a password text box, like this:
<asp:TextBox ID="PINPad" runat="server" Columns="6" MaxLength="4"
CssClass="PINTextClass" TextMode="Password"></asp:TextBox>
Then whenever the page posts back, the text box is cleared out on the screen and the textbox is empty (though during the timer event, the value does make it back to the server.)
Any suggestions how to fix this, so that it retains its value during postback?
As a security feature, ASP.NET tries to disallow you from sending the password value back to the client. If you're okay with the security issues (i.e. it's either not really secure information or you're sure that the connection is secure), you can manually set the "value" attribute of the control, rather than using its Text property. It might look something like this:
this.PINPad.Attributes.Add("value", this.PINPad.Text);
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (!(String.IsNullOrEmpty(txtPwd.Text.Trim())))
{
txtPwd.Attributes["value"]= txtPwd.Text;
}
if (!(String.IsNullOrEmpty(txtConfirmPwd.Text.Trim())))
{
txtConfirmPwd.Attributes["value"] = txtConfirmPwd.Text;
}
}
}
here is another way to do it:-
using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebControlLibrary
{
public class PWDTextBox : TextBox
{
public PWDTextBox()
{
this.TextMode = TextBoxMode.Password;
}
public string Password
{
get
{
string val = (string)ViewState["pwd"];
if (string.IsNullOrEmpty(val))
{
return "";
}
else
{
return val;
}
}
set
{
ViewState["pwd"] = value;
}
}
public override string Text
{
get
{
return Password;
}
set
{
Password = value;
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
this.Text = Password;
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
writer.AddAttribute(HtmlTextWriterAttribute.Value, this.Password);
}
}
}
The problem of losing the password in the postback can be avoid making use of Asynchronous JavaScript calls, lets describe a typical scenario for a Login page:
Lets say we have a Login page which allows the user to change the language of its labels when the user choose a language with a dropdownlist
a solution would be to invoke selectedIndexChanged event of the dropdownlist, make a postback which goes to the server and picks up the labels in the chosen language.
in this scenario the field password will be lost due to the security feature of ASP.NET which makes passwords fields not persisted between a postbacks.
This scenario can be solved if the postback is avoided making use of Asynchronous JavaScript Technology and XML (Ajax) calls.
Add a javascript function which will be invoked from the dropdownlist control, in this case this function is assigned to the Command property of the dropdownlist in code behind:
function ValueChanged(div)
{
var table = div.getElementsByTagName("table");
if (table && table.length > 0)
{
var t = table[0].getAttribute('type');
if (t != null && (t == "DropDown"))
{
var inputs = div.getElementsByTagName("input");
if (inputs && inputs.length == 2)
{
{
Translate(inputs[1].value);
}
}
}
}
}
The Translate function takes as parameter the selected option language in the dropdown control and performs the asynchronous call as shown bellow.
function Translate(lang)
{
var request = null;
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest();
if (request.overrideMimeType)
{
request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject)
{
request = new ActiveXObject("Msxml2.XMLHTTP");
}
if (request == null)
{
return;
}
var url = "GetLoginTranslations.aspx";
request.open('GET', url +'?lang=' + lang, true);
request.setRequestHeader("Cache-Control", "no-cache");
request.setRequestHeader("Pragma", "no-cache");
request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
request.onreadystatechange = function () { TranslateLabels(request); };
request.send(null);
}
the function Translate shown above performs the call and get the results in the specified .aspx page (in this case "GetLoginTranslations.aspx")
when the request is completed and the request.onreadystatechange is set to the function TranslateLabels this function will be executed.
on this way the postback is not executed as before in the event onSelectedIndexChanged of the dropdownlist control.
the TranslateLabels function would look something like :
function TranslateLabels(request)
{
if (request.readyState == 4)
{
if (request.status == 200)
{
if (request.responseXML)
{
var objRoot = request.responseXML.documentElement;
if (objRoot)
{
if (objRoot.nodeName == "strings")
{
for (var i = 0; i < objRoot.childNodes.length; i++)
{
var node = objRoot.childNodes[i];
var elem;
switch (node.getAttribute("id"))
{
case "lbl_login":
elem = document.getElementById("lbl_login");
if (elem)
elem.innerHTML = node.firstChild.nodeValue;
break;
}
///....
}
}
}
}
}
}
the request.responseXML contains the XML built in the page GetLoginTranslations.aspx and the structure of this XML is defined there.
the Page_Load() event in the GetLoginTranslations.aspx should look like:
protected void Page_Load(object sender, EventArgs e)
{
if (Request["lang"] != null)
strLang = Request["lang"];
//init response
Response.Clear();
Response.Cache.SetExpires(DateTime.Now);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetValidUntilExpires(true);
Response.ContentType = "application/xml";
Response.Charset = "utf-8";
XmlTextWriter xml = new XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8)
{
Formatting = Formatting.None
};
xml.WriteStartDocument();
xml.WriteStartElement("strings");
xml.WriteStartElement("string");
xml.WriteAttributeString("id", "lbl_login");
xml.WriteString(GetTranslation("label_login", strLang));
xml.WriteEndElement();
// ... the other labels
xml.WriteEndElement(); //</strings>
xml.Close();
}
Some other considerations:
set the the property AutoPostback of the dropdownlist to false.
Happens both for view-model properties named 'Password' and 'PIN'. You can bypass the behavior by defining those as:
string Password ;
... rather than:
string Password { get; set; }
If you do so, features such the 'LabelFor' macro displaying 'DisplayAttribute.Name' no longer works, so you'd have to define those directly in the HTML.
Or you can simply name the fields something other than 'Password' or 'PIN'.

Resources