Add ASP.NET Image from Page Method - asp.net

I am making an Ajax request with data to a Page Method in my code behind in my ASP.NET Web Forms application. I have a Panel control in my aspx page but I cannot get the control from that Page Method with its ID. I can get it from the Page_Load event though. What can I do to get the Panel control from the page method or is it not possible or maybe an alternative?
<asp:Panel ID="pnlImages" runat="server"></asp:Panel>
<script type="text/javascript">
function GetProductId() {
$.ajax({
type: "POST",
url: "Default.aspx/GenerateQrCode",
data: "{'Products':" + JSON.stringify(data) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
},
success: function (msg) {
alert('Success');
}
});
}
</script>
[WebMethod]
public static void GenerateQrCode(List<Product> Products)
{
foreach(var product in Products)
{
string qrCodeLocation = products.Where(pid=>pid.ProductId == product.ProductId).Select(s=>s.QrCode).FirstOrDefault().ToString();
Image image = new Image();
image.ID = product.ProductId.ToString();
image.ImageUrl = qrCodeLocation;
//Cannot get 'pnlImages' here
}
}

You won't be able to do that, WebMethod doesn't follow the same flow as normal page methods. It's not even a instance method but static.
You'll have to return the information on client and create the image there using javascript.

Related

How can I call a public function from a public shared function in asp.net?

I have this code:
Default.aspx(javascript:)
<script type="text/javascript">
function ShowChartSpider(group_id) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/MethodToCreateChart",
dataType: "json",
data: "{'parameter1':" + JSON.stringify(group_id) + "}",
success: function (data) {
alert("all correct");
console.log(data);
},
error: function (data) {
alert(data);
console.log(data);
}
}
);
}
</script>
Default.aspx.vb
<WebMethod()>
Public Shared Function MethodToCreateChart(parameter1 As String)
WebChartControl1.Series("sectorbuys").Points.Add(New SeriesPoint("value1", "156"))
WebChartControl1.DataBind()
End If
Return ""
End Function
The code in view aspx from the chart is:
<dxchartsui:WebChartControl ID="WebChartControl1" runat="server">
// some code
</dxchartsui:WebChartControl>
So in MethodToCreateChart I can't call my WebChartControl1, but if remove shared I can call the WebChartControl1 control, but the ajax method stops working, so how can I call a control in my aspx keeping my
Public Shared Function MethodToCreateChart?
PageMethod/WebMethod can access the session state but can't access the controls on the page, we can transfer the related property of control as a parameter that you want to get on WebMethod when you call WebMethod on the client.

WebMethod access page control and set value

My page name
public partial class AtamaGorevDegistir : System.Web.UI.Page
{}
My webmethod ajax side
var path = getLocation(location.href);
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
// data: "{" + str + "}",
contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
}
});
My webmethod
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string KisiBilgiDoldur(string KayitID, string TeklifID)
{
AtamaGorevDegistir atama = new AtamaGorevDegistir();
atama.AtananSuren.Value = "123";
return null;
}
But my problem my Control is null . But i can access this method but didnt set value and give error message. Why this happened?
WebMethod and ScriptMethod can't access the controls collection of the calling page. Think of it as outside the normal Web Forms lifecycle. When you use AJAX, you need to pass all data to the server side method it needs, and your server side should return all data that the client side needs. Then the client side should take that returned data and manipulate the DOM as necessary to display the result.
In your WebMethod, return the data instead of trying to assign it to a control, remove the return null;.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string KisiBilgiDoldur(string KayitID, string TeklifID)
{
return "123";
}
In your client side success handler, get the returned data and set the value of the control using JavaScript.
var path = getLocation(location.href);
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
// data: "{" + str + "}",
contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
//set control value to data.d here
}
});
You don't set the control value with a webmethod. Your return a value and from the api and do something with it, in the browser. Working with webmethods are not like webforms. The value you return in your webmethod is null... you're setting that null value into 'dd' in js, but you don't do anything with it. When you get your value back from the webmethod you need to do something with it. try 'alert(data.d)' in your success callback to see what i mean. Then $('#elm').text(data.d) if you want it on the page.
You should add parameters to data.
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
data:JSON.stringify({ KayitID: '1', TeklifID:'2' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
}
});

Html or Aspnet button on ColorBox Popup Redirect to another aspx page on button click

I am stuck with a critical issue.Can some one please suggest.
I have an .ascx page on which there is a pop up which has an aspnet button which must redirect to another page on click.
I followed the following steps:
On ascx page after opening colorbox, this function is called on clicking the button.
$.ajax({
type: 'POST',
url: "/HomeLoan/ProductConfirmationPop_SaveData.aspx/btnSaveData",
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
alert(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + textStatus + errorThrown);
}
});
On aspx page
[WebMethod]
public static void btnSaveData()
{
function sahil();//this function i want to call after this function is being called
}
I am getting Json parse error.
I removed dataType:json and made it return a html/text then it is giving me object object error.
This would propably be a lot easier if you could use a simple html form, add the value to a hidden input when onsubmit is triggered, and post it to a webservice which will redirect for you.
Anyway:
You need to decorate your btnSaveData method with another attribute and change the return type / parameter to string (or any other type that suits your needs):
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public static string btnSaveData(string color)
{
// do sth with the color
return "/SaveSuccess.aspx";
}
And in js:
// retrieve the color as a string (this is up to you - I don't know what sort of ColorPicker you're using, so this is a placeholder)
function saveColor()
{
var color = $('#myColorPicker').color.toString();
// create the data for the webmethod,
// the parameternames have to be the same as they are on the WebMethod
var colorData = "{ color:'" + color + "'}";
$.ajax({
type: 'POST',
url: "/HomeLoan/ProductConfirmationPop_SaveData.aspx/btnSaveData",
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: colorData,
success: function (response) {
window.location.href = response.d; // redirect on success
},
error: function (response, text, error)
{
alert(response + ' ' + text + ' ' + error);
}
});
Hope this helps and works!

Call a method in an aspx page

Can I call a method which is in an asp.net web page (in aspx.cs page) without checking it in the pageload?
for example '../test2.aspx/TestMethod
In this link I have noticed that we can give url: "PageName.aspx/MethodName", in jquery ajax method. I have tried it and never works for me.
Page Methods is a new mechanism in ASP.Net application where the server code cab be bound to Asp.Net pages
To enable Page methods we need to drag a ScriptManager control to the page and mark
the EnablePageMethods to “True”.
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnablePageMethods="True">
</asp:ScriptManager>
Go the Code behind file of the page and add a static method
[WebMethod]
public static string HelloWorld(string name)
{
return string.Format("Hi {0}",name);
}
In javascript function we can use PageMethods object to call the WebMethod of the page.
<script type="text/javascript">
function GreetingsFromServer() {
var name = 'Jalpesh';
PageMethods.HelloWorld(name,OnSuccess, OnError);
return false;
}
function OnSuccess(response) {
alert(response);
}
function OnError(error) {
alert(error);
}
</script>
you can use ajax call for another page webmethod
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});

JQuery and ASP.Net

Well im trying to return a more complex type than a string or bool but i fail what am i doing wrong?
JavaScript
<script language="javascript" type="text/javascript">
///<Reference Path="~/Script/jquery-1.3.2-vsdoc.js" />
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Test.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.Name);
},
failure: function() { alert("Failed") }
});
});
});
</script>
C# (This is not a webservice just a normal webpage)
[WebMethod]
public static ImageDC GetDate()
{
ImageDC dc = new ImageDC();
dc.Id = 1;
dc.Name = "Failwhale";
dc.Description = "Hurry the failwale is going to eat us!";
dc.IsPublic = true;
return dc;
}
I'm not sure what version .NET your running, but there is a breaking change with object returned from a web service. Check out this article.
http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
If you use fiddler to look at the request/response, it should be easy to tell if this is the problem.
http://www.fiddler2.com/fiddler2/
You should return a string.
return "dc = {Id:"+dc.Id+", Name:" + dc.Name +", Description: " +dc.Description + ", IsPublic: " +dc.IsPublic "}";

Resources