I have a simple question.
I have a FormView, with a save button. When the button is clicked, it saves to databse.
I've added an EXT message box to confirm if user wants to save the data or not. when he click yes on the messagebox yes button, then it should save the data.
I can't find where to write the yes button logic in the ext.
Here is my code :
<asp:FormView ID="myform" runat="server" DataSourceID="mydatasource" DefaultMode="Edit" DataKeyNames="Id" >
<EditItemTemplate>
<asp:TextBox ID="myText" runat="server" TextMode="MultiLine" ClientIDMode="Static"
Text='<%#Bind("xx") %>' />
<ext:Button ID="btn_Update" runat="server" AutoPostBack="false" CausesValidation="false" CommandName="Update" Text="Speichern" StyleSpec="float: left; margin-left:10px;"> <DirectEvents>
<Click OnEvent="btnUpdateClick"></Click>
</DirectEvents>
</ext:Button>
<script type="text/javascript">
function showResult(btn)
{
Ext.example.msg('Button Click', 'You clicked the {0} button', btn);
};
function showResultText(btn, text)
{
Ext.example.msg('Button Click', 'You clicked the {0} button and entered the text "{1}".', btn, text);
}
var showResult = function (btn) {
Ext.Msg.notify("Button Click", "You clicked the " + btn + " button");
};
var showResultText = function (btn, text) {
Ext.Msg.notify("Button Click", "You clicked the " + btn + 'button and entered the text "' + text + '".');
};
</script>
protected void btnUpdateClick(object sender, DirectEventArgs e)
{
X.Msg.Confirm("Confirm", "Are you sure you want to save?", new JFunction { Fn = "showResult" }).Show();
}
I guess you are looking for this: (Can be placed in any Demo-Box of the Sencha API)
Edit 2
I have totally overseen that you are using Direct. You should mention such things.
Is there any reason for using DirectEvent? I couldn't test it but how about this (the wrapping function may be unnecessary, but a normal ExtJS handler get button reference as first argument):
<form runat="server">
<ext:ResourceManager runat="server" />
<script runat="server">
[DirectMethod]
public void SetTimeStamp(string field)
{
// do your saving
}
</script>
<ext:TextField ID="TextField" runat="server" FieldLabel="Label"/>
<ext:Button ID="Button" runat="server" Text="Click Me" Icon="Lightning">
<Listeners>
<Click Handler="function() {Ext.Msg.show({title: 'Save?', msg: 'Do you want to save the data?:', buttons: Ext.Msg.YESNO,fn: function(btn){ if(btn == 'yes') {App.direct.SetTimeStamp(#{TextField}.getValue());}}})}" />
</Listeners>
</ext:Button>
</form>
Edit 1 Simply use Ext.Ajax.request()
Ext.Msg.show({
title: 'Save?',
msg: 'Do you want to save the data?:',
buttons: Ext.Msg.YESNO,
fn: function(btn, text){
Ext.Ajax.request({
url: 'yourUrl',
method: 'POST',
params: {
// your params
},
success: function() {
console.log('success');
},
failure: function() {
console.log('woops');
}
});
}
});
Form example removed
Thank you all for your support, I found my way through your answers I will put it here maybe it can be useful for someone.
First, button code, need to have Isupload = "true"
ext:Button ID="btn_Update" runat="server" AutoPostBack="false" CausesValidation="false"
CommandName="Update" Text="Save" StyleSpec="float: left; margin-left: 10px;"
AutoScroll="False">
<DirectEvents>
<Click OnEvent="btnUpdateClick" IsUpload="true" AutoDataBind="true">
</Click>
</DirectEvents>
</ext:Button>
in the button event in the aspx :
protected void btnUpdateClick(object sender, DirectEventArgs e)
{
MessageBoxButtonConfig buttonYes = new MessageBoxButtonConfig();
buttonYes.Text = "Yes";
buttonYes.Handler = "Ext.net.DirectMethods.ClickedYES();";
MessageBoxButtonConfig buttonNo = new MessageBoxButtonConfig();
buttonNo.Text = "NO";
// buttonNo.Handler = "Ext.net.DirectMethods.ClickedNO();";
MessageBoxButtonsConfig yesNoButtons = new MessageBoxButtonsConfig();
yesNoButtons.Yes = buttonYes;
yesNoButtons.No = buttonNo;
X.Msg.Confirm("Save Changes", "Would you like to Save?", yesNoButtons).Show();
}
Last the Yes method that will save to database:
[DirectMethod]
public void ClickedYES()
{
Formview.UpdateItem(false);
Formview.DataBind();
}
I would suggest that instead of wiring the yes button of the dialog to perform the postback. You should wait for the message box to close and then invoke the postback functionality if the user clicked yes.
For example:
Ext.Msg.prompt('SaveChange', 'Would you like to save the changes?:', function(btn, text){
if (btn == 'yes'){
__doPostBack('btnSubmit','OnClick');
}
});
Replace btnSubmit with the name of your button.
Although the above solution would be my recommended approach, you could, alternatively, use jquery by doing:
$('btnSubmit').trigger('click');
Source: http://dev.sencha.com/playpen/docs/output/Ext.MessageBox.html
Related
I have a textbox, on click, it allows you to select date from calendar control. If the date is deleted, it should uncheck the checkbox available just next to the textbox.
With below code, I am able to achieve everything other than making the textbox readonly so that user is not able to type anything. Also, once the text is selected, checkbox gets checked but when text is deleted the checkbox doesn't get unchecked.
Can anyone suggest what needs I might be doing wrong here ?
<asp:CalendarExtender ID="CalForDate" runat="server" TargetControlID="txtDate" Format="MM/dd/yyyy" PopupPosition="BottomLeft" DefaultView="Days"></asp:CalendarExtender>
<asp:TextBox runat="server" ID="txtDate" AutoPostBack="true" EnableViewState = "false" onKeyPress="javascript:return ChkCheckBox()" OnTextChanged="txtDate_OnTextChanged"></asp:TextBox>
The javascript code:
function ChkCheckBox() {
var txtDate = document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_txtDate').value;
if (txtDate.length == 9) {
document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_chkDate').checked = true;
}
else
{
document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_chkDate').checked = false;
}
In pageload I have added:
if (!IsPostBack){
txtDate.Attributes.Add("readonly", "readonly");}
And on text changed:
public void txtDate_OnTextChanged(object o, EventArgs e){
if (!(string.IsNullOrEmpty(txtDate.Text)))
{
chkDate.Visible = true;
chkDate.Checked = true;
}
else
{
chkDate.Visible = true;
chkDate.Checked = false;
} }
You can easily achieve this using jquery. I am sending you the sample code. Please don't hesitate to ask further assistance if needed.
<script type="text/javascript">
$(document).ready(function () {
$('#txtDate').on('change', function () {
//console.log('Tested');
if ($(this).val().toString().trim() != '') {
$('[Id*=ckTest]').attr('checked', 'checked');
}
else {
$('[Id*=ckTest]').removeAttr('checked');
}
});
$('#btnClear').click(function () {
$('#txtDate').val('');
$('#txtDate').trigger('change');
});
});
</script>
The code file is as below.
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:TextBox ID="txtDate" runat="server" ReadOnly="true" ClientIDMode="Static"></asp:TextBox>
<asp:CheckBox ID="ckTest" runat="server" />
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate" />
<button id="btnClear">Clear</button>
</div>
</form>
Just add jquery to project i used
jquery-2.1.4.min.js
It seems I am struggling with the order of the page life cycle. Based on the user selecting button 1 or 2, I need to have respective controls added dynamically during the Page_Load event. My problem is when a button is clicked the Page_Load event is executed before Button_Click event code is read. There for my variable "doWhat" is not assigned a value until after the Page_Load event. How can I have the "doWhat" variable assigned a value to be read during the Page_Load?
Below is asp.net form code for the two buttons:
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" onclick="Button_Click" />
<asp:Button ID="Button2" runat="server" Text="Button 2" onclick="Button_Click" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
Below is the code behind:
int doWhat;
protected void Page_Load(object sender, EventArgs e)
{
doWhat = Convert.ToUInt16(ViewState["doWhat"]);
if (doWhat == 1)
{
// code to dynamically load group 1 controls
}
else
{
// code to dynamically load group 2 controls
}
Label1.Text = Convert.ToString(doWhat);
}
protected void Button_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn.ID == "Button1")
{
doWhat = 1;
}
else
{
doWhat = 2;
}
ViewState.Add("doWhat", doWhat);
}
If you are comfortable with javascript then you can achieve it by making following changes in your design and code. Add a hidden field in your aspx page. Your HTML code should be like this.
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button_Click" OnClientClick="return doWhatAction(1);" />
<asp:Button ID="Button2" runat="server" Text="Button 2" OnClick="Button_Click" OnClientClick="return doWhatAction(2);" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:HiddenField ID="HiddenField1" Value="1" runat="server" />
<script type="text/javascript">
var doWhatAction = function (actionIndex) {
//alert(actionIndex);
document.getElementById("<%=HiddenField1.ClientID%>").value = actionIndex;
return true;
}
</script>
</div>
</form>
And your code will be something like...
int doWhat;
protected void Page_Load(object sender, EventArgs e)
{
//doWhat = Convert.ToUInt16(ViewState["doWhat"]);
doWhat = Convert.ToUInt16(HiddenField1.Value);
if (doWhat == 1)
{
// code to dynamically load group 1 controls
}
else
{
// code to dynamically load group 2 controls
}
Label1.Text = Convert.ToString(doWhat);
}
protected void Button_Click(object sender, EventArgs e)
{
//Do Nothing
//Button btn = sender as Button;
//if (btn.ID == "Button1")
//{
// doWhat = 1;
//}
//else
//{
// doWhat = 2;
//}
//ViewState.Add("doWhat", doWhat);
}
You can use jquery or javascript i this case.
Took on hidden variable in form
initialize it on click event of button in javascript
Read value of hidden variable in page load
<head >
<title>Hidden Variable</title>
<script type="text/javascript">
function SetHDNValue()
{
var hdnControlID = '<%= hdnControl.ClientID %>';
document.getElementById(hdnControlID).value=1;
}
</script>
</head>
<body >
<form id="form1" runat="server">
<div>
<input id="hdnControl" type="hidden" runat="server" />
<asp:Button ID="btnJSValue" Text="Click" runat="server" OnClientClick="SetHDNValue()"
/>
</div>
</form>
</body>
And in code behind file hdnControl.value
Since long ago I am not working with asp.net forms. And forgot doing things.But I found how you can do. As on stackoverflow link like answers is wrong. I copied main statements from the link which indicate how post-back events works and how you can use it for your purpose. For more http://aspsnippets.com/Articles/How-to-find-the-control-that-caused-PostBack-in-ASP.Net.aspx
All controls accept Button and ImageButton use JavaScript for causing a postback. To enable postback on these controls one has to set AutoPostBack property to true.
When you set this property to true, __doPostBack function is called on event which causes a postback.
The __doPostBack function is not visible in Source of the page until you place a LinkButton or set AutoPostBack to true for any of the above discussed controls.
Here is how generated __doPostBack looks:
<script type = "text/javascript">
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
</script>
The __doPostBack function simply stores the below two arguments in two hidden fields
eventTarget – The name of the control that caused the postback
eventArgument – The argument to be sent to server.
In two hidden fields which also appear only when AutoPostBack is set to true
Finally, here is how you can distinguish by getting control's ID that caused the postback :
if (IsPostBack)
{
string CtrlID = string.Empty;
if (Request.Form["__EVENTTARGET"] != null &&
Request.Form["__EVENTTARGET"] != string.Empty)
{
CtrlID = Request.Form["__EVENTTARGET"];
/****implement Your logic depending on control ID****/
}
}
I have a requirement to do some logic execution upon change of dropdownlist value. Before executing the logic i need to take user confirmation and then call service side method to complete the process. Not sure How to call server side method based on modal popup confirmation response from user. So if user confirms with Yes button on the modal popup server side code should be called otherwise do nothing.
Here is the code i have . Server side does not get called upon modal popup confirmation.
function PopupDialog(title, text) {
var div = $('<div>').html('<br>'+text).dialog({
title: title,
modal: true,
height: 190,
width: 320,
buttons: {
"Yes": function () {
$(this).dialog('close');
},
"No": function () {
$(this).dialog('close');
}
}
});
return true;
};
<asp:GridView runat="server" ID="grdTransactions" SkinID="gridviewskin"
AllowSorting="true" AllowPaging="true" PageSize="30" Width="100%"
OnRowDataBound="grdTransactions_RowDataBound"
OnDataBound="grdTransactions_DataBound"
OnSelectedIndexChanged="grdTransactions_SelectedIndexChanged">
.............
<asp:TemplateField Visible="true" HeaderText="Status" >
<ItemTemplate>
<asp:Label runat="server" ID="lblStatus" Visible="False" Text='<%# ShowStatus( Container.DataItem ) %>' />
<asp:DropDownList ID="ddlTransactionList" AutoPostBack="True" OnSelectedIndexChanged="ddlTransactionList_SelectedIndexChanged" onchange="return PopupDialog('Remittance Confirmation','Are you sure you want to update the status?.');" runat="server"></asp:DropDownList>
<br/>
</ItemTemplate>
</asp:TemplateField>
**Server Side Code --**
protected void ddlTransactionList_SelectedIndexChanged(object sender,
EventArgs e)
{
//Your Code
if (OnDataChanged != null)
OnDataChanged(sender, e);
}
Thank you
I think there is a conflict between the javascript created by ASP.NET and the onchange event you are adding to the dropdown (onchange="return .... ") so it is ignoring the the call that posts back.
I would start by trying something like this on the front end:
// remove the autopostback & onchange from the ddl definition
<asp:DropDownList ID="ddlTransactionList" runat="server"></asp:DropDownList>
function PopupDialog(title, text) {
var div = $('<div>').html('<br>'+text).dialog({
title: title,
modal: true,
height: 190,
width: 320,
buttons: {
"Yes": function () {
$(this).dialog('close');
return true;
},
"No": function () {
$(this).dialog('close');
}
}
});
};
$(document).ready(function(){
$("<% ddlTransactionList.CLientID %>").change(function(){
if(PopupDialog('Remittance Confirmation','Are you sure you want to update the status?.')){
__doPostBack('ddlTransactionList')
}
});
});
In the code-behind:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"]; // parameter
// Request["__EVENTTARGET"]; // ddlTransactionList
// make your call to ddlTransactionList_SelectedIndexChanged() here
}
Let us know if this helps.
Here i am trying to do a email validation for a textbox using jquery and am calling that function on onclientclick and i have a button click event too.But the button click event is firing before the javascript function.I need to validate the textbox before firing the button click event.Here is my code
$(document).ready(function () {
$("#MainContent_txtEmail").blur(function () {
ValidateEmail();
});
function ValidateEmail()
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddress = $("#MainContent_txtEmail").val();
if (!emailReg.test(emailaddress)) {
$("#emailspan").html('<font color="red" size=2px;>Please enter valid Email address</font>');
return false;
}
else {
$("#emailspan").html('<font color="red"></font>');
return true;
}
}
});
and
<asp:TextBox ID="txtEmail" name="txtEmail" runat="server" CausesValidation="false" TextMode="Email">
</asp:TextBox><span id="emailspan" value="0"></span>
<asp:Button ID="btnsubmit" CssClass="btn pdf-submit" runat="server" Text="SEND" OnClientClick="return ValidateEmail();" OnClick="btnsubmit_Click"/>
and my event
protected void btnsubmit_Click(object sender, EventArgs e)
{
SendSmtpEmail(txtEmail.Text, "noreply#a.net", "test", "test-template");
}
Any suggestion??
hey In your code ::
`$("#MainContent_txtEmail").blur(function ()
why you are calling the function you may have to change that in to
$("#txtEmail").blur(function ()`
this will work I guess !!
You'll want to remove the OnClick for btnsubmit
<asp:Button ID="btnsubmit" CssClass="btn pdf-submit" runat="server" Text="SEND" OnClientClick="return ValidateEmailThenSubmit();" />
Then click the btnsubmit manually in code after the validation.
function ValidateEmailThenSubmit()
{
ValidateEmail();
$("#" + <%= btnsubmit.ClientID %>).click();
}
Why use javascript? Just use the asp.net RegularExpressionValidator like so:
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
More info here http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.regularexpressionvalidator.aspx
The ValidateEmail() method is not visible being declared inside the anonymous method passed as argument to the $.ready() method.
Get the ValidateEmail method outside $(document).ready and it should work.
I have Repeater control like this;
<asp:Repeater ID="repeaterCategoryList" runat="server"
onitemcommand="repeaterCategoryList_ItemCommand">
<ItemTemplate>
<td class="center">
<asp:Button ID="buttonDelete" runat="server" CssClass="btn btn-primary" CommandName="Delete" Text="Delete"
CommandArgument='<%# Eval("CategoryId") %>'/>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
And my code behind page looks like this;
protected void repeaterCategoryList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
//my server side logic here
}
}
And my javascript code in .aspx file looks like this:
<script>
$(function () {
$('#buttonDelete').live('click', function (e) {
e.preventDefault();
$.alert({
type: 'confirm'
, title: 'Alert'
, text: '<p>Are you sure, you want to delete this category</p>'
, callback: function () {
// call server side here
}
});
});
});
</script>
How do I call the repeater delete command logic inside my javascrpt?
Is there any alternative way to do this?
You can use ItemDatabound property of repeater to bind the Javascript function to Dalete Button Onclick event as follow...
CodeBehind:-
void Repeater1_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
int IdToBeDeleted=((Label)e.Item.FindControl("idFieldControl")).Text;
Button Btn= (Button)e.Item.FindControl("buttonDelete");
Btn.Attributes.Add("onclick","return ConfirmDelete('"+IdToBeDeleted+"')");
}
}
Javascript:
<script>
function ConfirmDelete(var idVal)
{
if(Confirm("Are you sure, you want to delete this category?"))
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST","DeletePage.aspx?id="+idVal,true);
xmlhttp.Send();
}
}
</script>
DeletePage.aspx:
function pageLoad(sender, eventArgs)
{
if(!IsPostBack)
{
int IdToBeDeleted=Request.QueryString["id"];
Write Your Delete Code Here...
if delete successful...Response.Write("Delete Successful");
}
}
Use OnClientClick in the button click
and write the function name in it. when the function returns false, then the server side method is not called. If the JS Function returns true, then the server side method is executed
<asp:Button ID="buttonDelete" runat="server" CssClass="btn btn-primary" CommandName="Delete" Text="Delete" onclick="Button_Click_Event" OnClientClick="return Javascript_Function()" CommandArgument='<%# Eval("CategoryId") %>'/>
OnClientClick, is the only way to get between a button and its post back.