JS Code:
<script type="text/javascript">
function ShowCurrentTime(name) {
PageMethods.GetCurrentTime(name, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</script>
HTML Code:
<asp:ImageButton ID="IMGBTN001" runat="server" ImageUrl="Images/ico/labaniat.png"
class="img-responsive em-img-lazy" OnClientClick="ShowCurrentTime('01')" />
<asp:Image class="img-responsive retina-img em-img-lazy" ID="IMGMostViewed" runat="server"ImageUrl="Images/Banner/block1_banner.jpg" />
Code Behind C#
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
//string x = IMGMostViewed.ImageUrl;
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
I want to access the Image from another class.
How can I access the IMGMostViewed this GetCurrentTime class?
i used this code, but get "page.FindControl("IMGMostViewed")" return null
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
if (HttpContext.Current != null)
{
Page page = (Page)HttpContext.Current.Handler;
Image IMGMostViewed = (Image)page.FindControl("IMGMostViewed");
string x = IMGMostViewed.ImageUrl;
}
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
Theoreticaly you can cast the CurrentHandler to your type of page and then access your button:
var currentHandler = HttpContext.Current.CurrentHandler as T;
currentHandler.IMGBTN001.ImageUrl = "abc";
The beter way would be to access your button on clientside in your success function.
function ShowCurrentTime(name) {
PageMethods.GetCurrentTime(name, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
//Access here your button and modify it
}
Here you also will find a related Answer:
How to access page controls inside a static web 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 am trying to call a method from my aspx page. This method is found on the aspx.cs page, but it is throwing an error. Do you know what's wrong, please?
ajax script
<script type="text/javascript">
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
} //Default.aspx
function insertMarker() {
var usernameName = 'username';
var usernameVal = document.getElementById('<%=hdnUsername.ClientID%>').value;
var latitudeName = 'latitudeStr';
var latitudeVal = document.getElementById('<%=hdnMarkerLatitude.ClientID%>').value;
var longituteName = 'longitudeStr';
var longitudeVal = document.getElementById('<%=hdnMarkerLongitude.ClientID%>').value;
var iconName = 'markerIcon';
var iconVal;
if (document.getElementById('blueMarker').checked) {
iconVal = 'images/blueMarker.png';
}
if (document.getElementById('greenMarker').checked) {
iconVal = 'images/greenMarker.png'
}
if (document.getElementById('pinkMarker').checked) {
iconVal = 'images/pinkMarker.png';
}
var titleName = 'name';
var titleVal = document.getElementById('<%=title.ClientID%>').value;
var descriptionName = 'description';
var descriptionVal = document.getElementById('<%=description.ClientID%>').value;
$.ajax({
type: "POST",
url: "mapping.aspx/insertNewMarker",
data: {"username" : usernameVal, "longitudeStr":longitudeVal, "latitudeStr" :latitudeVal, "markerIcon":iconVal, "name" : titleVal, "description" :descriptionVal},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
Website Design
Save Marker
Title
Description
Save
Aspx.cs Method.
[ScriptService]
public partial class mapping: System.Web.UI.Page
{
[WebMethod]
private static void insertNewMarker(string username, string longitudeStr, string latitudeStr, string markerIcon, string name, string description)
{
//My Code
}
}
Your server-side webmethod cannot be private, you have to change it to public.
From MSDN documentation on webmethods:
When you create a Web service in managed code, you indicate the
methods that are available through that Web service by placing the
WebMethod attribute before the method declaration of a Public method.
Private methods cannot serve as the entry point for a Web service
although they can be in the same class and the Web service code can
call them.
Change your data like this
data:JSON.stringify({username : usernameVal, longitudeStr:longitudeVal, latitudeStr :latitudeVal, markerIcon:iconVal, name : titleVal, description :descriptionVal}),
You need to pass data as json stirng which has a specific format. If you use JSON.stringify data will be convetred to json string and if you don't use this than you have to pass every paremter and its value in quotes like this.
data:"{username:'" + usernameVal + "',............}",
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.
I want to set the Image URL of Image control using client side code and save the image to the server using C# code. Here is what i have implemented:
<asp:Button ID="btnImageUpload" OnClick="btnImageUpload_Click" runat="server" Text="Preview" CausesValidation="false" OnClientClick="Image_View();"/>
C# Code:
protected void btnImageUpload_Click(object sender, EventArgs e)
{
if (Directory.Exists(#"C:\\Images"))
SaveImage_Server();
else
{
Directory.CreateDirectory(#"C:\\Images");
SaveImage_Server();
}
}
public void SaveImage_Server()
{
try
{
if (FlUpldImage.PostedFile.ContentLength > 0)
{
String fn = Convert.ToString(DateTime.Now) + Path.GetFileName(FlUpldImage.FileName);
if (fn.Contains('/'))
{
fn = fn.Replace("/", "");
}
if (fn.Contains(':'))
{
fn = fn.Replace(":", "");
}
if (fn.Contains(" "))
{
fn = fn.Replace(" ", "");
}
String Saved_ImagePath = #"C://Images/" + fn; // making the path with created dynamically folder name
FlUpldImage.SaveAs(Saved_ImagePath);
HidnLocalImageURL.Value = Saved_ImagePath;
}
}
catch (Exception re)
{
}
}
JavaScript
function Image_View() {
// __doPostBack('<%= btnImageUpload.ClientID %>', '');
// var clickButton = document.getElementById("<%= btnImageUpload.ClientID %>");
// clickButton.click()
var idFlUpload = '<%= FlUpldImage.ClientID %>';
var fu1 = document.getElementById(idFlUpload);
var idImgCntrl = '<%= imgCorrect.ClientID %>';
var ImgCntrl = document.getElementById(idImgCntrl);
alert("You selected " + fu1.value);
ImgCntrl.setAttribute('src', fu1.value);
}
Now my issue is that once the server side code is executed the page gets refreshed and the link set to Image control using JS gets reset to default value.
How can i get this working wherein the image also gets saved and Image URL property also gets set through JS.
If there is any other way to implement this than please let me know. Thanks in Advance!
You have to set it on server too. You can use hidden field to save the url and access that hidden field on server to get the url to set mgCntrl.ImageUrl
In html
<input type="hidden" runat="server" id="hdnImageSrc" />
On Client javascript
hdnImageSrc = document.getElementById('<%= hdnImageSrc.ClientID %>');
mgCntrl.setAttribute('src', fu1.value);
hdnImageSrc.value = fu1.value;
On server side code
mgCntrl.ImageUrl = hdnImageSrc.Value;