Passing a string from IHttpHandler to Javascript and then to Silverlight - c#

I am using a handler to act as a proxy between a server with a string (actually a xml but I am trying for a string) and my Silverlight app. I have written the handler and it properly collects the string(xml). The problem I am having is converting that string from the JSON into a string that javascript can pass back to my Silverlight code.
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var xmlReturn = new String("");
function xmlStart() {
$.getJSON('xmlProxy.ashx', function (data) {
setXml(data);
});
}
function setXml(data) {
xmlReturn = data;
}
function getXml() {
alert(xmlReturn);
return xmlReturn;
}
Silverlight:
private void button1_Click(object sender, RoutedEventArgs e)
{
HtmlPage.Window.Invoke("xmlStart");
string test = (String)HtmlPage.Window.Invoke("getXml");
textBox1.Text = test;
}
Just in case the handler code (baseurl taken out for security):
namespace HttpHandler_Proxy
{
public class xmlProxy : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
WebClient getCap = new WebClient();
string baseurl = "some_url";
string response = getCap.DownloadString(baseurl);
context.Response.ContentType = "application/json";
context.Response.Write(response);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
I am relativity new to both Javascript and jQuery so this may be a trivial question and for that I apologize. On this version of the code it never sets xmlReturn to anything other than ""
I have done other versions but the code is always returned to Silverlight as null/undefined/"".

Your content type is set to json, but you don't seem to be doing any encoding, i.e. turning the response from the server into valid json. Try adding something like:
response = new JavaScriptSerializer().Serialize(response);

Why not try using $.load instead of getJSON if you don't intend on treating that string as json at that point.
Edit
First, you should check the value of data inside your success callback (console.log(data)). Make sure your server-side code is returning what you intend it to.

Related

How to use the client side(JS) variable in c#?

I have the following JS code.
var thisItem = document.thisItem;
var e-mail = thisItem.getProperty("email");// which gets the e-mail of the User
And I have the following C# code.
public static void Main()
{
string username = "username";
string email = "";
//code to send a mail to the user
}
In JS code I' m using applyMethod("CSProgramName"); to run the C# from client side.
Here I want to use the Javascript 'e-mail' variable in C# code. How Can I do this?
This is not possible.
Have some hidden text box and assign the value through javascript and access the control.
If it is ASP.Net I would suggest to use ajax post to your C# code like below.
var reqUrl = "http://mysite/Sample/Sample.aspx?post=true";
var jqXHRresponse;
var request = $.ajax({
url: reqUrl,
type: "POST",
data: {email:emailAddress},
dataType: 'json'
});
protected override void OnInit(EventArgs e)
{
if (Request.Params["post"] == "true")
{
string email = Request.Params["email"];
}
}

How to get the value that is returned from the kendoui upload success or complete function

I am using Kendo UI upload control. I have defined the Kendo UI upload like this:
<input type="file" name="resume" />
$("#file").kendoUpload({
async: {
saveUrl: "/Home/SaveResume",
autoUpload: true
},
complete: function (e)
{
// here i want to get the text that is returned from the controller
}
});
The controller code is like:
public ActionResult SaveResume(HttpPostedFileBase resume)
{
var text;
// code for the file to convert to text and assign it to text
return Json(text, JsonRequestBehavior.AllowGet);
}
After returning the code I want to retrieve the code in complete function. How can I do that?
You can get the response to success function like this
function onSuccess(e)
{
var response = e.response.data();
}
where the return json could be
return Json(new { data = text }, "text/plain");
If you just passing a string back you should be able to do:
function onSuccess(e) {
var text = e.XMLHttpRequest.responseText;
}
You could also pass back a more complex object, if required:
// Object
public class MyObject
{
public int ID { get; set; }
public string Text { get; set; }
}
// Controller Action
public virtual ActionResult Upload(HttpPostedFileBase file)
{
return this.Json(new MyObject(), "text/plain");
}
// Javascript Handler
function onSuccess(e) {
var response = jQuery.parseJSON(e.XMLHttpRequest.responseText);
var id = response.ID;
var text = response.Text;
}
I'll add my answer alongside the other valid answers here. First though you will want to get the returned response in the success function instead of the complete function:
$("#files").kendoUpload({
async: {
saveUrl: url,
removeUrl: removeUrl,
autoUpload: true
},
select: onFileSelect, // function for when a file is selected
success: onFileSuccess, // function that returns response after upload
complete: onFileComplete, // function after success
remove: onFileRemove, // function for when a file is removed
});
The on success function returns an object (normally people name it e)
function onFileSuccess(e) {
console.log("e.response", e.response);
console.log("e.operation", e.operation);
console.log("e.XMLHttpRequest.status", e.XMLHttpRequest.status);
//e.operation is upload or remove
if (e.operation === "upload") {
// a file was added, get the response
var fileid = e.response;
} else {
// Do something after a file was removed
}
}
My console.log entries return this data:
console.log values
This is how I return my data from the server:
public HttpResponseMessage InsertTempFile()
{
HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[0];
//........
// Code that adds my file to the database
// and generates a new primary key for my file
//.........
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(myNewId.ToString());
return response;
}
The response.Content returns my new Id in e.response
The HttpStatusCode.Ok returns my status of 200. There's a bunch of other data that is returned as well if you inspect the response.
Note that to use HttpResponseMessage and HttpStatuseCode you need to include the following namespaces in your class:
using System.Net.Http;
using System.Net;

Ajax call not returning response from c# code

Here is my jquery code
var ajaxUrl = "AjaxCallHandler.aspx";
function _init_Chart() {
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: ajaxUrl, // Location of the service
data: "OpCode=GetCallAverageReportForGraph&Parms=DeptId^17~Month^10~Year^2012", //Data sent to server
contentType: "", // content type sent to server
dataType: "string", //Expected data format from server
processdata: true, //True or False
success: function (responseString) {//On Successful service call
alert(responseString);
}
});
return false;
}
Here is my c# code
protected void Page_Load(object sender, EventArgs e)
{
string responseMessage = "";
string status = "SUCCESS";
try
{
if (Request.QueryString["OpCode"] == null)
{
throw new Exception("Invalid Request, OpCode missing.");
}
string operationRequested = Request.QueryString["OpCode"];
string Params = Request.QueryString["Parms"];
switch (operationRequested)
{
case "GetCallAverageReportForGraph":
responseMessage = GetCallAverageReportForGraph(Params);
break;
case "GetCallAverageReportDetails":
responseMessage = GetCallAverageReportDetails(Params);
break;
}
}
catch (Exception exp)
{
status = "EXCEPTION";
responseMessage = exp.Message;
}
Response.ClearContent();
Response.ClearHeaders();
Response.Write(responseMessage);
}
I tried putting a breakpoint in the c# code. It is writing Response.Write from c# code but I'm unable to receive the response in jquery code. Can any one point out the issue?
Change the data type string to html or leave it empty for default type
Refer http://api.jquery.com/jQuery.ajax/
There a lot of missing things in your code.
You need to a static method marked with the attribute WebMethod:
[WebMethod]
public static RetrunValue Foo()
{
...
}
The data must be in json format in asp.net.
You should read this article
Write the code in code behid in this way.
Response.Clear();
Response.Write("Your response in string");
Response.End();
Please not that if your response is in HTML you have to pass the string in Response.Write("Your String"), If your response is in Json Format write your code like this.
string json = JsonConvert.SerializeObject(List<object> of your code);
Response.Clear();
Response.Write(json);
Response.End();

AjaxRequest.get( ) not accepting text/Html from Response.Write() function

i am using AjaxRequest.Get() method from AjaxRequest.
following is the inline javascript in analysis.aspx
function getAnalysis(type) {
var innerHtml;
AjaxRequest.get(
{
'url': 'getAnalysis.aspx?type=' + type
, 'onSuccess': function (req) { innerHtml = req.responseText; }
}
);
document.getElementById("div_analysis").innerHTML = innerHtml;
}
when getAnalysis(type) is called in analysis.aspx everything goes fine - ajax request is properly submitted and response is send properly. But at the end value of innerHTML remains undefined.
Following is the code of getAnalysis.aspx -
protected void Page_Load(object sender, EventArgs e)
{
if(type == "somwthing") str = load();
Response.Clear();
Response.CacheControl = "no-cache";
Response.Write(str);
Response.End();
}
When i debugged javascript using google chrome, i found that value of innerHMTL is undefined, although everything went fine.
So i dont understand why AjaxRequest class is not accepting text output from Reponse.Write().
P.S. : I have also tried Response.ContentType = "text/Html"; and Reponse.Fluch().
please guide me thnx in advance.
You need to set the div contents in the onsuccess function since it is called asynchronously when the AJAX request completes
function getAnalysis(type) {
var innerHtml;
AjaxRequest.get(
{
'url': 'getAnalysis.aspx?type=' + type
, 'onSuccess': function (req) { document.getElementById("div_analysis").innerHTML = req.responseText; }
}
);
}

How to know if the request is ajax in asp.net in Application_Error()

How to know if the request is ajax in asp.net in Application_Error()
I want to handle app error in Application_Error().If the request is ajax and some exception is thrown,then write the error in log file and return a json data that contains error tips for client .
Else if the request is synchronism and some exception is thrown ,write the error in log file and then redirect to a error page.
but now i cant judge which kind the request is . I want to get "X-Requested-With" from header ,unfortunately keys of headers don't contain "X-Requested-With" key ,why?
Testing for the request header should work. For example:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult AjaxTest()
{
throw new Exception();
}
}
and in Application_Error:
protected void Application_Error()
{
bool isAjaxCall = string.Equals("XMLHttpRequest", Context.Request.Headers["x-requested-with"], StringComparison.OrdinalIgnoreCase);
Context.ClearError();
if (isAjaxCall)
{
Context.Response.ContentType = "application/json";
Context.Response.StatusCode = 200;
Context.Response.Write(
new JavaScriptSerializer().Serialize(
new { error = "some nasty error occured" }
)
);
}
}
and then send some Ajax request:
<script type="text/javascript">
$.get('#Url.Action("AjaxTest", "Home")', function (result) {
if (result.error) {
alert(result.error);
}
});
</script>
You can also wrap the Context.Request (of the type HttpRequest) in a HttpRequestWrapper which contains a method IsAjaxRequest.
bool isAjaxCall = new HttpRequestWrapper(Context.Request).IsAjaxRequest();
it is possible to add custom headers in the client side ajax call. Refer http://forums.asp.net/t/1229399.aspx/1
Try looking for this header value in the server.
You could use this.
private static bool IsAjaxRequest()
{
return HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
}

Categories