I have written the script dynamically using string builder as follows
public static void ShowMessage1(ENUM_MessageType pMessageType, string pMessage, Button c)
{
StringBuilder strScript = new StringBuilder();
strScript.Append("<script type=\"text/javascript\" src=\"").Append("/Scripts/jquery-1.4.1.js").Append("\"></script>");
strScript.Append("<script type=\"text/javascript\" src=\"").Append("/Scripts/jquery.msgBox.js").Append("\"></script>");
strScript.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"").Append("/Styles/msgBoxLight.css").Append("\" />");
strScript.Append("<script type=\"text/javascript\">");
strScript.Append("(function example()");
strScript.Append("{");
strScript.Append("$.msgBox({");
strScript.Append("title:'" + lMessageType + "'");
strScript.Append(",");
strScript.Append("content:'" + pMessage + "'");
strScript.Append(",");
strScript.Append("type:'" + lOptionType + "'");
strScript.Append(",");
strScript.Append("buttons: [{ value: 'Yes' }, { value: 'No'}],");
strScript.Append("success: function (result) {");
strScript.Append("if(result == 'Yes'){");
strScript.Append("javascript:_doPostBack('" + c.ClientID + "','');");
strScript.Append("}");
strScript.Append("}");
strScript.Append("});");
strScript.Append("})();");
strScript.Append("</script>");
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(enumClass), "info", strScript.ToString());
}
}
I am getting the exception as ReferenceError: _doPostBack is not defined can some one help me
Its should javascript currently you have
strScript.Append("avascript:_doPostBack('" + c.ClientID + "','');");
It should be:
strScript.Append("javascript:__doPostBack('" + c.ClientID + "','');");
Missing j in front. Also make sure that its __ not a single underscore.
Looks like you're missing an underscore on your __doPostBack() call.
Also, take a look at the success in your rendered JS:
(function example() {
$.msgBox({
title : 'INFORMATION',
content : 'I am from client side',
type : 'confirm',
buttons : [{
value : 'Yes'
}, {
value : 'No'
}
],
success : function (result) {
if (result == 'Yes') {
javascript : __doPostBack('Button1', ''); // <--- this line
}
}
});
})();
If you are just trying to call a postback there, get rid of the javascript : so that it reads like this:
strScript.Append("__doPostBack('" + c.ClientID + "','');");
Also, according to the answer on this SO question, make sure there is an ASP.NET WebControl rendered to the page. __doPostBack() is automatically included on the page when a WebControl is rendered. So, if you on't have one on the page, there's a chance that the __doPostBack() method could be missing.
If you don’t have any asp.net server side postback controls on the page the “_doPostBack not defined” error will be thrown on the client. To avoid the described error you can try adding following lines of code into the page load event:
protected override void OnPreLoad(EventArgs e)
{
this.Page.ClientScript.GetPostBackEventReference(this, string.Empty);
base.OnPreLoad(e);
}
The GetPostBackEventReference returns a string that can be used in a client event to cause postback to the server
The other approach is to add hidden asp:Button which will register the same scripts as GetPostBackEventReference method.
Related
I have an application where I am getting some value over ajax post method and sending to [WebMethod] static method code behind. But I cannot assign the value to the textbox of the page. Here is my code:
[WebMethod]
public static string copyData(string name, string msg, string sing_cal1, string timepick, string timepickst, string sing_cal4, string step)
{
if (step == "3")
{
if (HttpContext.Current != null)
{
Page page = (Page)HttpContext.Current.Handler;
TextBox txtCampaignNameEditC = (TextBox)page.FindControl("txtCampaignNameEdit");
TextBox txtMsgEditC = (TextBox)page.FindControl("txtMsgEdit");
TextBox txtSentFromC = (TextBox)page.FindControl("txtSentFrom");
Label lblScheduledTimeC = (Label)page.FindControl("lblScheduledTime");
txtCampaignNameEditC.Text = name; // Here I am getting error as "Object reference not set to an instance of an object."
}
}
return "";
}
<script type="text/javascript">
$(document).ready(function () {
$('#wizard').smartWizard({ onLeaveStep: leaveAStepCallback, onFinish: onFinishCallback });
function leaveAStepCallback(obj) {
var step_num= obj.attr('rel');
var name = $("#<%= txtCampaignName.ClientID %>").val();
var msg = $("#<%= txtMessage.ClientID %>").val();
var cal1 = $("#<%= single_cal1.ClientID %>").val();
var timepicks = $("#<%= txtTimePick.ClientID %>").val();
var pickst = $("#<%= txtTimePickST.ClientID %>").val();
var cal4 = $("#<%= single_cal4.ClientID %>").val();
$.ajax({
type: "POST",
url: "CreateCampaign.aspx/copyData",
data: '{name: "' + name + '", msg: "' + msg + '", sing_cal1: "' + cal1 + '", timepick: "' + timepicks + '", timepickst: "' + pickst + '", sing_cal4: "' + cal4 + '", step: "'+ step_num +'"}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
return true;
}
This code behind method does not let me to assign the received parameter to the textbox. Please help me on this. Thanks.
The only time the code behind has access to modify controls is during the page life cycle. Once the page has been rendered the page is no longer connected to the server.
Moving code that references controls from the WebMethod to another function will not work because there are no controls. You must return data from the web method and place the data in the DOM using JavaScript.
To be more clear, I will say that you can't assign values to textbox using [WebMethod], because [WebMethod] don't run the ASP.Net page lifecycle. You need to use JavaScript to assign values to a textbox.
For tutorials on how to get and set textbox values with JavaScript you can check: this or this
Set the ClientIDMode property of the textbox to Static. That will ensure that whatever ID you set for the textbox will also be the id on the client. That way the id will be predictable and you can refer to it from JavaScript.
Then in your client code after the ajax is executed you can update the value in JavaScript.
document.getElementById("yourControlId").value = "whatever";
In my Asp.Net(C#) web page, I am doing 95% work from Jquery Ajax. Only Print work is happening from server side code because it needs to redirect another page for print. Here is my print button code
protected void btnprint_Click(object sender, ImageClickEventArgs e)
{
string status = "Normal";
string Id = txtReceiptNo.Text;
string BillType = "BillReceipt";
string Url = "BillReceipt.aspx";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ApprovalHistory", "window.open('BillReceiptReport.aspx?Id=" + Id + "&Status=" + status + "&BillType=" + BillType + "&Url=" + Url + "', '_blank');", true);
}
When I click Print Button it redirect to printpage with some values in another tab.
But the problem is, when I click Print button Postback happens and everything disturbed in my webpage because as I mentioned above I am doing 95% work using Jquery Ajax.
So I decided to do 100% work from Jquery Ajax and tried to call this print functionality inside Static, WebMethod but I found that RegisterClientScriptBlock is not working inside Static Method. I am trying to do something like this......
[WebMethod]
public static void PrintReport()
{
string status = "Normal";
string Id = "40";
string BillType = "BillReceipt";
string Url = "BillReceipt.aspx";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ApprovalHistory", "window.open('BillReceiptReport.aspx?Id=" + Id + "&Status=" + status + "&BillType=" + BillType + "&Url=" + Url + "', '_blank');", true);
}
Please help me guys....
ScriptManager.RegisterClientScriptBlock((Page)(HttpContext.Current.Handler), typeof(Page), "ApprovalHistory", "window.open('BillReceiptReport.aspx?Id=" + Id + "&Status=" + status + "&BillType=" + BillType + "&Url=" + Url + "', '_blank');", true);
You are using this (non-static) inside your static method i.e. in PrintReport() method
The keyword 'this' returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class.
Please try to use the below code:
[WebMethod]
public static void PrintReport()
{
string status = "Normal";
string Id = "40";
string BillType = "BillReceipt";
string Url = "BillReceipt.aspx";
if (HttpContext.Current.CurrentHandler is Page)
{
Page page = (Page)HttpContext.Current.CurrentHandler;
if (ScriptManager.GetCurrent(page) != null)
{
ScriptManager.RegisterStartupScript(page, typeof(Page), "ApprovalHistory", "window.open('BillReceiptReport.aspx?Id=" + Id + "&Status=" + status + "&BillType=" + BillType + "&Url=" + Url + "', '_blank');", true);
}
else
{
page.ClientScript.RegisterStartupScript(typeof(Page), "ApprovalHistory", "window.open('BillReceiptReport.aspx?Id=" + Id + "&Status=" + status + "&BillType=" + BillType + "&Url=" + Url + "', '_blank');", true);
}
}
}
This is not gonna work for you. You are registering a client script block inside a webmethod. client script block runs on page load whereas in ajax call page doesn't reload so its neither giving you any error nor its running your script block. you can adopt two approaches to solve this problem.
1: Do not register any script block inside your web method , just simply return values from your web method e.g (Id, status, BillType,Url) and inside the success block of your ajax call open the new page which you were trying to open from inside your webmethod.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "Accounts.aspx/PrintReport",
data: JSON.stringify(Param),
type: "POST",
success: function (data)
{
var Id=data.d.Id;
var status=data.d.status;
var BillType=data.d.BillType;
var Url=data.d.Url;
var win=window.open("BillReceiptReport.aspx?Id="+Id+ "&Status="+status+"&BillType="+BillType +"&Url="+ Url +"",'_blank');
win.focus();
}
});
2: Second approach is that do not use any ajax call at all , use an anchor tag instead of button and in the href attribute of of anchor tag give your page link with the query string values. like this
<a class='btn' href='BillReceiptReport.aspx?id="+ $("#txtReceiptNo").Text+"' target='_blank';>Click Me</a>
Hope it helps.
I have a view with a hidden field
#Html.HiddenFor(model => model.Driver.ID, new { htmlAttributes = new { id = "driver" } })
I have a controller with a method I want to call passing that field "driver", but debugging I see this method doesn't even get called.
public string GetEditWarningMessage(int? driverID)
{
Driver driver = unitOfWork.DriverRepository.Get().Where(d => d.ID == driverID).FirstOrDefault();
string message = null;
if(!driver.Status.Equals("A"))
{
message = "This driver is assigned to current or future schedule movements";
}
return new JavaScriptSerializer().Serialize(message);
}
and finally the javascript, which I'm sure is the source of the problem
$().ready(function () {
$("#driver").change(function () {
$.get("../GetEditWarningMessage/" + $(this).val() + '?' + $.now(), function (response) {
var warning;
warning = $.parseJSON(response);
});
$("form").submit(function () {
var performEdit = false;
if (warning != null) {
performEdit = confirm(warning);
return performDelete;
}
});
});
});
basically if the message I pass from the GetEditWarningMessage() is null, I don't want the popup to appear, otherwise have it popup with the warning message passed on.
Help much appreciated, thank you all
Change the following
$.get("../GetEditWarningMessage/" + $(this).val() + '?' + $.now(), function (response) {
var warning;
warning = $.parseJSON(response);
});
To
var warning;
$.get("../GetEditWarningMessage/" + $(this).val() + '?' + $.now(), function (response) {
warning = $.parseJSON(response);
});
In your code the variable "warning" has scope inside only $.get call. So it cannot be used in form submit call..
Declaring it outside the $.get call will solve the issue.
If the hidden input value doesn't change then you must call GetEditWarningMessage inside the form submit call.. even that Synchronous ajax call so that form submittion can wait for the response of warning message.
I want to show confirm dialog from code be hind.
I have a comfirm dialog A. when I click button OK on A, it was call to the method B in code be hind(using ajax post: url/B and B is a method has webmethod attribute).
In method B I want to show other dialog, and code is flowing:(B is AlertInformLogOut )
[WebMethod]
public static void AlertInformLogOut(string alertId, string option)
{
//TODO: Open call schedule
var page = HttpContext.Current.Handler as Page;
// PopUp alert notify info
if (page != null)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "script", "AlertSetDialog(" + new JavaScriptSerializer().Serialize(new AlertInformEntity()) + ", 'AlertInforms');", true);
//ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "script", "AlertSetDialog(" + new JavaScriptSerializer().Serialize(new AlertInformEntity()) + ", 'AlertInforms');", true);
}
}
problem is: Dialog not showing.
Can some body tell me why, and can I showing dialog from a method has webmethod attribute.
The problem is, as I recall, a WebMethod wont update the page, unlike an ASP:update panel call back.
As you are using jQueries ajax function, use the success call back there, instead of trying to do it server side.
$.ajax({
type: "POST",
url: url+"/UpdateAlertInfo",....,
success: /*Call you Confirm Function Here */
}
You may alss want to consider using $.post() insteado
I designed an application which works in all browser except in IE,
Actually where i got struck means i added 2 tabs for example,
public string GetTabs()
{
strResult = strResult + "<div class='amc-container'>";
strResult = strResult + "<div id='links-div' class='simple-round-div-right'>";
strResult = strResult + "<div id='tab-link1' class='tab-button-enabled'>Products</div>";
strResult = strResult + "<div id='tab-link2' class='tab-button-disabled'>Spares</div> </div></div>";
return strResult;
}
//Javascript function
function showTab(div, dom, obj, tcd, tid,status) {
$("div.tab-button-enabled").removeClass('tab-button-enabled').addClass('tab-button-disabled');
$(obj).parent().removeClass('tab-button-disabled').addClass('tab-button-enabled');
$("#" + div).html('Loading...');
$.get("/common/get_amcb.aspx", { dm: dom, acd: tcd, aid: tid, domain: obj.firstChild.nodeValue,status:status },
function (data) {
$("#" + div).html(data);
});
}
$.get() function loads page get_amcb.aspx page & get the data from .aspx page through response.Write() method & bind into the div.
while page loading I'm calling this function (GetTabs()) & assigning to label.
All this works in chrome,Firefox but not in IE if I'll use IE(9.0 version) then added data is not reflect into the tab if we want to show data means we need close browser & reopen the browser that time added data is showed, WHY its happening & I'm not getting whats going on behind please help me.
Thanks
IE loves caching. Clear cache and see. If that is the case, send a timestamp along with the url. So it will be considered a s anew request.
var tstmp = new Date();
var uniqueTimeStamp = tstmp.getTime()
$.get("/common/get_amcb.aspx?timestam="+uniqueTimeStamp , { dm: dom, acd: tcd, aid: tid, domain: obj.firstChild.nodeValue,status:status },
function (data) {
$("#" + div).html(data);
});