$.get function not calling in IE - c#

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);
});

Related

FileContentResult not generating file when called from AJAX post

I apologize if this is a little vague, however the issue presenting itself isnt giving too much away. I have been writting an application that uses MigraDoc to generate PDFs. The controller method used to generate and download the PDF is as follows:
public FileContentResult ConvertToPDF(int reportTypeId, string cultureName, int headerFooterTemplateId, int baseClassId, string baseTypeName)
{
try
{
string resourcePath = #"C:\TFS\Products\EnGenero\Trunk\EnGenero Application\RiskNetResources\bin\Debug\RiskNetResources.dll"; // --<<-- Reference this
byte[] result = new DocumentWriter().ConvertDocumentToPDFSharp(GetSeedData(reportTypeId, cultureName, resourcePath, headerFooterTemplateId, baseClassId));
return new FileContentResult(result, "application/pdf")
{
FileDownloadName = "MyReportFile.pdf"
};
}
catch (Exception ex)
{
Logger.Instance.LogError("Error in ConvertToPDF", ex);
return new FileContentResult(GetBytes("Error fetching pdf, " + ex.Message + Environment.NewLine + ex.StackTrace), "text/plain");
}
}
During development this has worked fine and when the above code is hit the PDF downloads through the browser fine. During development I was calling this controller method directly from a JQuery dialog box with Hard Coded parameters.
However, I further developed the application and now call this action method through an Ajax Post in a partial view.
function CreateDocumentPDF() {
var baseClassId = #Html.Raw(Json.Encode(ViewData["baseClassId"]));
var baseTypeName = #Html.Raw(Json.Encode(ViewData["baseTypeName"]));
var reportTypeId = $j('#ddlReportType option:selected').attr('Value');
var branchId = $j('#ddlBranch option:selected').attr('Value');
var languageId = $j('#ddlLanguage option:selected').attr('Value');
$j.ajax({
url: appRoot + 'DocumentPDFPrinter/ConvertToPDF',
type: 'post',
data: { 'reportTypeId': reportTypeId, 'cultureName': languageId, 'headerFooterTemplateId': branchId, 'baseClassId': baseClassId, 'baseTypeName': baseTypeName },
success: function (data) {
closeDefaultPopup();
},
failure: function () {
alert("Error Generating PDF.");
}
});
}
The same exact same parameter values are passed and the controller action runs through as expected however now there is no file generated/downloaded.
I can only imagine it is something to do with the Ajax post as this is the only difference between it running fine or not from what I can see.
This is the response I am getting - looks okay as far as I can see...? Am I missing anything?
So I simply moved away from the AJAX call and instead am now calling:
window.location = appRoot + "DocumentPDFPrinter/ConvertToPDF?reportTypeId=" + reportTypeId + "&cultureName=" + languageId etc...
Which seems to do the job nicely.

How to set value to textbox from static method in asp.net?

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";

AJAX path is not right

I have a web application with a few cascading dropdown lists. So I use ajax to update the value of the next dropdown list. I put the javascript script in a separate file.
// Code that triggers when there is a change in Activity drop down.
$('#ActivityId').change(function () {
var activityId = $(this).val();
// Empty the Workstation.
$('#WorkstationId').empty();
$('.showhide-workstation').show();
var url = "~/WorkOrderSubmissions/GetWorkstationsByActivityJson";
// AJAX call that re-populate Workstation drop down depending on the Activity selected.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: { activityId: activityId },
success: function (codes) {
$('#WorkstationId').append('<option value=""></option>');
$.each(codes, function (i) {
$('#WorkstationId').append('<option value = "' + codes[i].Value + '">' + codes[i].Text + '</option>');
});
},
error: function (ex) {
$('#WorkstationId').append('<option value=""></option>');
}
}); // END $.ajax() on GetRejectCodesByActivityJson
}); // END $('#ActivityId').change()
The code works when I run it from inside Visual Studio. It does not work when I deploy it to my local web server. I deploy it to
http://localhost/mea
When I open Developer Tools in Chrome, I see the error.
POST http://localhost/~/WorkOrderSubmissions/GetLinesByWorkorderJson 404 (Not Found)
I tried to to change the url to
url = ~/WorkOrderSubmissions/GetLinesByWorkorderJson
url = /WorkOrderSubmissions/GetLinesByWorkorderJson
url = WorkOrderSubmissions/GetLinesByWorkorderJson
None of them work. I thought ~ is supposed to go to the root of the web application, which is http://localhost/mea.
The ~ syntax is only recognised by ASP.Net; it will be taken literally by any JS code. You need to provide the URL via your C# code to JS:
var url = '#Url.Content("~/WorkOrderSubmissions/GetWorkstationsByActivityJson")';
Or better yet:
var url = '#Url.Action("GetWorkstationsByActivityJson", "WorkOrderSubmissions")';

Is it possible to use RegisterClientScriptBlock in Static Method in asp.net C#?

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.

_doPostBack not defined

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.

Categories