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;
});
Related
I am using Ajax to call some method from database
this method takes parameters from the page
and gets some values from the DB
I want to populate the result to the page controls by accessing these controls in the web method.
Below is my code. I am using collapsible panel extender. On click event it collapses & should call verifyFunction method written in code behind.
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePageMethods="True"></asp:ToolkitScriptManager>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
<asp:CollapsiblePanelExtender ID="cpeSOP" runat="Server" CollapseControlID="LinkButton1"
CollapsedSize="0" Collapsed="True" CollapsedImage="~/imgages/addRow.gif"
ExpandControlID="LinkButton1" ExpandDirection="Vertical" ExpandedImage="~/imgages/addRow.gif"
ImageControlID="Image1" SuppressPostBack="true" TargetControlID="Panel1">
<!-- JAVASCRIPT CONTENT -->
<script type="text/javascript">
function pageLoad(sender,args){
$find("collapsibleBehavior").add_expandComplete( expandHandler );
$find("collapsibleBehavior").add_collapseComplete( collapseHandler );
}
function expandHandler( sender , args ){
alert('I have expanded');
// NewPlanBudget.aspx/verifyFunction
$.ajax(
{
url: "NewPlanBudget.aspx/verifyFunction",
data: "flag=1",
success: function (msg) {
if (msg.d) {
alert("Sucess");
}
}
});
}
function collapseHandler( sender , args ){
alert('I have collapsed');
}
The code behind is
[WebMethod]
protected void Page_Load(object sender, EventArgs e)
{
cpeSOP.BehaviorID = "collapsibleBehavior";
}
public static void verifyFunction()
{
LinkButton1.Text = "Hello";
}
i think you cannot access page controls in web method but you can return the results to ajax and have to get the results
and also post your sample code, i dont know why are you calling page load in web-method,
and also the script must be
$.ajax(
{
url: "NewPlanBudget.aspx/verifyFunction",
data: {flag="1"},
success: function (msg) {
if (msg.d) {
alert("Sucess");
}
}
});
and you must get the value in web-method as
public static void verifyFunction(string flag)
{
}
and give name to link-button in design page itself
as
<asp:LinkButton ID="LinkButton1" Text="Hello" runat="server">LinkButton</asp:LinkButton>
public static void Savedata() {
if (HttpContext.Current != null) {
Page page = (Page)HttpContext.Current.Handler;
TextBox TextBox1 = (TextBox)page.FindControl("TextBox1");
}
}
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;
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.
first of all apologies for my english.
I'm a newby in json area.
My problem is that i can't parse the data recived in a json response into a asp:LinkButton or whatever asp:element, coz i can't create a correct sintax.
Especifically, What I'm trying to do, is this:
<script type="text/javascript">
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", { cmd: "getMakes", min_year:"1941", max_year:"2012"}, function (data) {
var makes = data.Makes;
for (var i = 0; i < makes.length; i++) {
($("<asp:LinkButton ID=\"lb" + i +"\" runat=\"server\" />").text(makes[i].make_display )).appendTo("#lbProva");
}
});
<script>
<ul id="lbProva" class="lb_prova" >
</ul>
I hope that someone could help me coz i've tryed many possibilities but no one was the right one.
Thank u in advance.
You can't create asp.net server controls in javascript on client side. If you want to use json data on client side, you must apply it to already generated html controls.
Actually, you can create server controls only on a server. So the question is how to pass AJAX call response to server and enforce it to refresh desired area on a page.
First variant
<script type="text/javascript">
$(function () {
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", { cmd: "getMakes", year: "2009" },
function (data) {
//The 'data' variable contains all response data.
var makes = $.map(data.Makes, function (make) { return make.make_display; }).join(";");
document.getElementById("<%= CarMakersHiddenField.ClientID %>").value = makes;
__doPostBack("<%= CarMakersUpdatePanel.ClientID %>", "");
});
});
</script>
<asp:UpdatePanel runat="server" ID="CarMakersUpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:HiddenField runat="server" ID="CarMakersHiddenField" />
<asp:BulletedList runat="server" ID="MakersList" DisplayMode="LinkButton">
</asp:BulletedList>
</ContentTemplate>
</asp:UpdatePanel>
Server code:
protected void Page_Load(object sender, EventArgs e)
{
MakersList.Items.Clear();
foreach (var maker in CarMakersHiddenField.Value.Split(';'))
{
MakersList.Items.Add(maker);
}
}
Second approach is more siutable if you need to pass to server some complex object like array of makers objects. In that case you can serialize this object to JSON string on client and deserialize it on server. Looks like previous version with bit changes:
<script type="text/javascript">
$(function () {
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", { cmd: "getMakes", year: "2009" },
function (data) {
//The 'data' variable contains all response data.
var serializedString = Sys.Serialization.JavaScriptSerializer.serialize(data.Makes);
document.getElementById("<%= CarMakersHiddenField.ClientID %>").value = serializedString;
__doPostBack("<%= CarMakersUpdatePanel.ClientID %>", "");
});
});
</script>
Markup left the same as in the first version.
Server code:
[Serializable]
public class Make
{
public string make_id;
public string make_display;
public bool make_is_common;
public string make_country;
}
protected void Page_Load(object sender, EventArgs e)
{
MakersList.Items.Clear();
if (!String.IsNullOrEmpty(CarMakersHiddenField.Value))
{
var serializer = new DataContractJsonSerializer(typeof(Make[]));
using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(CarMakersHiddenField.Value)))
{
var makes = serializer.ReadObject(stream) as Make[];
if (makes != null)
{
foreach (var maker in makes)
{
MakersList.Items.Add(new ListItem(maker.make_display, maker.make_id));
}
}
}
}
}
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'.