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";
Related
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 webmethod that returns a json string and populates a jstree and all works perfectly the 1st click of a text box. Each time a user clicks a different text box, it passes different values in the jquery but the webmethod actually doesn't get called after the 1st time it's called. So I'm wondering what I need to clear in order for it do call the webmethod each time.
function showtree1(thisID, line) {
$('#jstree_demo_div').jstree.empty;
$('#jstree_demo_div').jstree({
"core": {
"data": //data - jquery
{
type: "POST"
, dataType: "json"
, contentType: "application/json; charset=utf-8"
, url: "FlowCycleReport.aspx/populateTree"
//, data: "{'imgID':'" + thisID + "'}"
, data: JSON.stringify({ imgID: thisID, line: line })
//, "data": function (node) {
// //return "{'id':'" + $(node).attr("id") + "'}";
// return node.d;
//}
, success: function (node) {
var ReturnString = node.d;
// alert(ReturnString);
return { "id": node.id };
}///success
, error: function (msg) {
alert("Error: " + msg.responseText);
}///error
}//data
}///core
,
"plugins": ["themes", "json_data", "search", "contextmenu", "types"]
});
}
WebMethod:
[WebMethod]
//public static string populateTree(string imgID, int node)
public static string populateTree(string imgID, string line)
{
DAL_Flow DL = new DAL_Flow();
//string line = "278";
string nodevalues = DL.JsonNav(imgID, line);
return nodevalues;
}
onclick event:
$(function () {
$(".textbox").click(function (e) {
var thisID = $(e.target).attr("ID");
var csID = thisID.substr(thisID.lastIndexOf("_") + 1);
$('#posDetailDiv').hide();
var line = $('#dlLine').val();
// Reset the header:
$('#PartHeaderDiv').empty();
$('#PartHeaderDiv').append('Line Number: ' + line + ': Control Station ' + csID);
showtree1(csID, line);
$('#posDetailDiv').show();
});
});
script manager:
<asp:toolkitscriptmanager runat="server" EnablePageMethods="true" ></asp:toolkitscriptmanager>
The values for CSID and line changes on my header each click but the treeview values don't.
I've put a breakpoint on the webmethod to verify that the webmethod isn't getting hit.
I'm sure I'm just missing something.
Can anyone help?
First thing i can think of is that since you wipe out everything and rebuild it every time it is clicked, your .click event gets wiped out too since it is not dynamically bonded. So instead of doing:
$(".textbox").click(function (e) {
you can do:
$(".textbox").on('click', function (e) {
//click event code goes here
});
so your click event would be registered all the time even for the dynamic .textbox elements that are added later on.
I'm having a lot of trouble making jQuery's autocomplete widget work for me. I am using a list of key/value pairs from a server.
I have the following requirements:
If the user set the id of the value, like he knowes the code of the city
and instad of typing the name of a city he put the code of the city-- I want that the autocomplete will put the name of the city, and it dosn't!!
I edit My Code, now it works!
I add this lines
if (data.d.length == 1 && request.term.match(/\d+/g))
SetValue(textbox, hidden, data.d[0]);
else
and the function function SetValue(textbox, hidden, value){
textbox.focus().val(value.Text);
hidden.val(value.Semel);}
Another thing is if one is using the same page for creation and editting - on reloading the page while editting, you have to recreate all the spans etc for the values, and I want to send from the server just the code of the autocomplete, not the text value, and I want when i will set the value into the textBox, the autoComplete will start to work and will bring the value from the server
But with this I get still stuck:
I Dont know how to trigger the “autocomplete” event with send the value (the request value)
Here is My C# code:
[WebMethod(EnableSession = true)]
[ScriptMethod]
public List<IEntityBase> FetchList(string Text, string Code, string Dspl, int NumRecordes, string TableName)
{
Text = Server.UrlDecode(Text);
List<Tavla> tvListById = null;
int ignored = 0;
if (int.TryParse(Text, out ignored))
tvListById = TvList.GetTvListById(TableName, ignored, Code, Dspl);if (tvListById != null && tvListById.Count != 0)
return tvListById.Cast<IEntityBase>().ToList();
var fetchShem = TvList.GetData(TableName, Code, Dspl)
.Where(m => m.Shem.ToLower().Contains(Text.ToLower()))
.Take(NumRecordes);
return fetchShem.Cast<IEntityBase>().ToList();
}
and here is my Jquery Code:
enter code here
textbox.autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/" + funcName,
data: "{ 'Text': '" + escape(request.term) + "','Code':'" + code + "','Dspl':'" + dspl + "','NumRecordes':'" + numrecordes + "','TableName':'" + tablename + "'}",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
if (data.d.length == 1 && request.term.match(/\d+/g))
SetValue(textbox, hidden, data.d[0]);
else
response($.map(data.d, function (item) {
return {
label: item.Text,
value: item.Semel
}
}));
}
},
error: function (msg) { alert(msg); }
});
},
minLength: minLength,
select: function (event, ui) {
var selectedObj = ui.item;
if (selectedObj) {
textbox.val(selectedObj.label);
hidden.val(selectedObj.value);
} return false; },
});function SetValue(textbox, hidden, value) {
textbox.focus().val(value.Text);
hidden.val(value.Semel);
}
For your first question, it all depends the logic you have tried , just in case if you have an id for any country then this shouldnt be any difficult.
Second query is all about performance of the page, this also shouldnt be any tougher if you try updating the elements based on the search pattern using ajax, where in you have to update just the realted elements,while keeping rest of your Page intact .
refer http://jquery.com/ for better understanding of the same
Unable to read the selected drop down list value on page load after pressing browser back button.But this happen only during the first function call.
I'll explain in details:
When a page loads initially i have attached an ajax javascript as shown below
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", "_Initialize_Chart();", true);
Below is the javascript AJAX function
function _Initialize_Chart() {
var selectedDeptId = $(ddlQueues).val();
var selectedMonth = $(ddlMonth).val();
var selectedYear = $(ddlYear).val();
$.ajax({
type: "GET",
url: ajaxCallHandlerUrl,
data: {
OpCode: "GetCallAverageMonthlyReportForGraph",
Params: "DeptId^" + selectedDeptId + "~Month^" + selectedMonth + "~Year^" + selectedYear
},
dataType: "xml",
beforeSend: function () {
$('#' + lblCallAverageDetails).html('');
document.getElementById(chartdiv).style.backgroundImage = "url('../images/ajax-loader_new_.gif')";
},
success: function (responseString) {
document.getElementById(chartdiv).style.backgroundImage = "";
_Load_Chart(responseString);
_Load_CallAverageGridData();
},
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert("There was an error Initializing Charts :: " + errorMessage);
}
});
}
function _Load_CallAverageGridData() {
var selectedDeptId = $(ddlQueues).val();
var selectedMonth = $(ddlMonth).val();
var selectedYear = $(ddlYear).val();
$.ajax({
type: "GET",
url: ajaxCallHandlerUrl,
data: {
OpCode: "GetCallAverageReportDetail",
Params: "DeptId^" + selectedDeptId + "~Month^" + selectedMonth + "~Year^" + selectedYear
},
dataType: "",
success: function (responseString) {
$('#' + lblCallAverageDetails).html(responseString);
},
error: function (xhr, errorType, exception) { //Triggered if an error communicating with server
var errorMessage = exception || xhr.statusText; //If exception null, then default to xhr.statusText
alert("There was an error Fetching Call Average Data :: " + errorMessage);
}
});
}
So this javascript loads the page content which is a graph and a grid.
On clicking the rows in the Grid, it navigates to another page.
Now on pressing the browser back button,the above shown javascript is initially called but the var selectedMonth = $(ddlMonth).val(); doesn't give me the value of the actually selected value in drop down list.
On Success of first Ajax call, another Ajax call _Load_CallAverageGridData(); is made in which i'm getting the value of var selectedMonth = $(ddlMonth).val(); correctly.
Can any one throw some light why this is happening.
your code in page load
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", "_Initialize_Chart();", true);
is not executed on page load, for it to excecute you need to use url hash function.
for it simply use this
where you click on product/image on page there call onclick javascript function i.e.
function getHashOnBack(valueget)
{
location.hash = "#backTo=" + $(window).scrollTop();$(document).height();
}
Now, put
$(document).ready(function ()
{
var ab = window.location.hash.substring(1).split("=");
if (ab[0] == "backTo")
{
// this would be called automatically when back putton pressed and hav #back=1234 etc. // value in url
$(window).scrollTop(parseInt(ab[1]));
}
}
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);
});