Execute command only after executing the javascript function - javascript

I have a button inside a repeater, and this is the event:
protected void Delete_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
string id = btn.CommandArgument;
string client = "011";
try
{ //When is done
ScriptManager.RegisterStartupScript(this, GetType(), "del", "Del(" + id + ");", true);
//do it
this.Repeater.DataSource = dal.GetT(client);
this.Repeater.DataBind();
}
catch { }
}
I need to update the repeater, only after executing the javascript function Del(id)
How can this be done in the best way?

Related

asp.net dynamically button with event handler wont work

Hi I create button to fire event when user click on row.
It works when I create that "hidden" buttons on master page but when I create those buttons on MainContent it won't fire the event:
List<Button> btnCollection = new List<Button>();
protected void OnRowTask(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string CellValue = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "id"));
string urlAddress = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "url_address"));
Button dummyBtn= new Button();
dummyBtn.Attributes["style"] = "display:none;";
dummyBtn.ID = "divBtn_" + CellValue;
dummyBtn.Text = urlAddress;
dummyBtn.Click += new EventHandler(this.rowButton_Click);
PlaceHolderForHiddenBtn2.Controls.Add(dummyBtn);
btnCollection.Add(divButton);
e.Row.Attributes.Add("onclick", "return rowclick(" + CellValue + ");");
}
Session["hiddenBtnCollectionTask"] = btnCollection;
}
Click event:
private void rowButton_Click(object sender, EventArgs e)
{
//some code to exectute
}
On page load I create the same buttons what was added on row created event:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["hiddenBtnCollectionTask"] != null)
{
List<Button> btnGenerateList = (List<Button>)Session["hiddenBtnCollectionTask"];
foreach (Button btn in btnGenerateList)
{
PlaceHolderForHiddenBtn2.Controls.Add(btn);
}
}
}
And JS function that should fire button.click() - event :
function rowclick(id) {
var button = document.getElementById('MainContent_divBtn_' + id);
button.click();
return false;
}
Any ideas?

Html button call a function in code behind and it fires only once

I have html button which calls a function in code behind and it fires only once.
I want it to fire event every time I click the button.
It is possibly duplicated but I have tried to add "!IsPostBack" but it doesn't work.
My ascx class:
<button runat="server" type="button" class="btn btn-report" onserverclick="OnReportBtnClick" id="reportBtn">
<i class="glyphicon glyphicon-floppy-disk"></i>
</button>
I have to use html button, not <asp:Button> because <asp:Button> doesn't let me to insert <i> tag inside.
Here is my code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
try
{
reportBtn.ServerClick += OnReportBtnClick;
}
catch (Exception ex)
{
}
}
}
//this method is called only once even I click the button many times afterwards.
protected void OnReportBtnClick(object sender, EventArgs e)
{
try
{
// Set file name
string pdfName = SPContext.Current.Web.Title + fileType;
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime startDate = DateTime.MinValue;
if (!string.IsNullOrEmpty(report_startDate_datePicker.Value))
startDate = DateTime.ParseExact(report_startDate_datePicker.Value, format, provider);
DateTime endDate = DateTime.MaxValue;
if (!string.IsNullOrEmpty(report_endDate_datePicker.Value))
endDate = DateTime.ParseExact(report_endDate_datePicker.Value, format, provider);
// Provisioning data for report
var report = GetReport(startDate, endDate);
// Merger data to template html
byte[] data = GetPdfData(htmlTemplate, report);
//Respond report to client
RenderResponse(pdfName, data);
}
catch (Exception ex)
{
LoggingService.LogError(LoggingService.NTT_ERROR,
string.Format("ERROR: {0} - SOURCE: {1} | {2}", ex.Message, ex.Source, System.Reflection.MethodBase.GetCurrentMethod().Name));
}
}
//I think the problem could be this method.
//I return a pdf file to client
private void RenderResponse(string pdfName, byte[] data)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + pdfName);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.BinaryWrite(data);
HttpContext.Current.Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
LoggingService.LogError(LoggingService.NTT_ERROR,
string.Format("ERROR: {0} - SOURCE: {1} | {2}", ex.Message, ex.Source, System.Reflection.MethodBase.GetCurrentMethod().Name));
}
You can use a LinkButton
<asp:LinkButton runat="server" ID="ReportBtn" Text="<i class='glyphicon glyphicon-floppy-disk'></i>" OnClick="ReportBtn_Click" CssClass="btn btn-report" />
in .cs page
protected void ReportBtn_Click(object sender, EventArgs e)
{
//your code
}
They do support html in the text field.

When I use window.location.href ,then my another function not calling .Following is my javascript code

I am using Following code..
When I click on the link, the javascript Hello() function is invoked
I want to use window.location.href
But when I use this the following __doPostBack('Button2_Click'), it does not work.
But when remove window.location.href from the following code then __doPostBack('Button2_Click') does work.
<script type="text/javascript">
function Hello(clicked_id) {
var abc = "http://localhost:2621/OrgChart.aspx?id" + clicked_id;
window.location.href = abc;
__doPostBack('Button2_Click');
return false;
}
</script>
<a id="A1" href="javascript:Hello();">LINK</a>
This is my code behind code...
public partial class WebForm17 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.GetPostBackEventReference(this, string.Empty);//This is important to make the "__doPostBack()" method, works properly
if (Request.Form["__EVENTTARGET"] == "Button2_Click")
{
//call the method
Button2_Click(this, new EventArgs());
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = "Method called!!!";
EmpInfo emp = new EmpInfo();
DA_EmpInfo da_emp = new DA_EmpInfo();
List<EmpInfo> lei = da_emp.GetAllEmployeeInfoByEmpId("MJ-IB-1");
DetailsView1.DataSource = lei;
DetailsView1.DataBind();
}
}
I guess, __doPostBack is making a request to the server and you break it by using window.location.href = abc;.
You should use some callback from this request to redirect to your url.
try to use setTimeOut function
setTimeout(function () {
window.location.href = abc;
}, 1000);
this will wait 1 second for finish of __doPostBack() function.
Or if you don't want to use timeOut, paste window.location.href = abc; line to end of the __doPostBack() function.

call javascript method from codebehind

how to call this javascript function from asp.net codebehind pageload..
<script type="text/javascript">
function abc() {
alert("Hello! I am an alert box!");
}
</script>
Is it possible to pass an integer array in to javascript function from asp.net codebehind pageload?
Try below code :
protected void Page_Load(object sender, EventArgs e)
{
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "abc", "abc();", true);
}
1. Update > Passing string parameter :
protected void Page_Load(object sender, EventArgs e)
{
var message = "hi";
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "abc", "abc('" + message + "');", true);
}
JavaScript Method with string parameter :
function abc(message) {
alert(message + ", I am an alert box!");
}
2. Update > Passing string parameter and numeric array to JS method:
protected void Page_Load(object sender, EventArgs e)
{
int[] numbers = { 10, 20, 30 };
string serializedNumbers = (new JavaScriptSerializer()).Serialize(numbers);
var message = "hi";
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "abc", "abc('" + message + "', " + serializedNumbers + ");", true);
}
JavaScript Method with string and numeric array parameters:
function abc(message, numbers) {
alert(message + ", I am an alert box!");
for (var i = 0; i < numbers.length; i++) {
alert(numbers[i]);
}
}
Regular Page
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "abc" + UniqueID, "abc();", true);
}
Ajax Page
You need to use ScriptManager if you use ajax.
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, GetType(),
"abc" + UniqueID, "abc();", true);
}
Try
Dim script As String = String.Format("abc()", "")
ScriptManager.RegisterClientScriptBlock(Me, GetType(Page), UniqueID, script, True)
Or simply
ClientScript.RegisterStartupScript(GetType(), "abc", "alert('Hello! I am an alert box!')", true);
You can't call a JavaScript function from the codebehind, but you can return a response that includes JavaScript that invokes the function when the page loads in the browser. Just make sure that your page includes
<script type="text/javascript">
function abc() {
alert("Hello! I am an alert box!");
}
abc();
</script>
That could be either as part of the ASPX page or you could register it as a script block in the codebehind.

how can I to get controls back on my first page after server.execute("../../abc.aspx"). I have to show an alert after server.execute()

This is my Code, After Server.Execute() my popup does not show.
protected void Generate_cola_letter(object sender, EventArgs e)
{
try
{
Server.Execute("../ABC.aspx");
}
catch (Exception exp)
{
}
finally
{
ScriptManager.RegisterStartupScript();
}
Are you trying to create a Message box?
this is an example of a message box in asp.net
string script = "alert(\"Your Message.\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);

Categories

Resources