Getting data from .aspx to jquery ajax - c#

I'm novice in jquery and I have one problem:
I have two .aspx files: one of them contain script
<script type ="text/javascript">
$(document).ready(function () {
var schemaName = GetURLParameters('schemaName');
var key = GetURLParameters('key');
$.post("dataloader.aspx", {
name: schemaName,
key: key
});
});
</script>
which send parameters to other page, "dataloader.aspx". Here is "dataloader.aspx.cs" code:
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json";
var schemaName = Request.Form["name"];
var key = Request.Form["key"];
Loader loader = ConnectionManager.getLoader();
Dictionary<string, string> name_value = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(schemaName))
{
var schema = loader.GetSchema(schemaName);
var qcontext = new SimpleLoader.BOService.QueryContext();
qcontext.InitQueryContext();
var element = loader.GetObjectByKey(schema, key);
var viselems = element._Schema.GetVisibleElems();
var cardElems = viselems.Where(x => !(x is SchemaElemDetail)).ToList();
foreach (var elem in cardElems)
{
var value = (element.GetValue(elem.Name) ?? "").ToString();
if (!string.IsNullOrEmpty(value))
{
name_value.Add(elem.Name, value);
}
}
Response.Write(name_value);
Response.Flush();
Response.End();
}
}
As you can see, I,m adding some data to dictionary. I want to send this dictionary to "clientcard.aspx" client side by jQuery, but i don't know how...Can you help me?? I'll be very grateful.

A way would be to call a webmethod in dataloader.aspx. Assuming your function's name would be getNameValue, in your aspx page, you'd have a webmethod like this : (You'd basically transfer the code from Page_Load event to this)
[System.Web.Services.WebMethod]
public static Dictionary<string, string> getNameValue(string name, string keyN)
{
var schemaName = name;
var key = keyN;
Loader loader = ConnectionManager.getLoader();
Dictionary<string, string> name_value = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(schemaName))
{
var schema = loader.GetSchema(schemaName);
var qcontext = new SimpleLoader.BOService.QueryContext();
qcontext.InitQueryContext();
var element = loader.GetObjectByKey(schema, key);
var viselems = element._Schema.GetVisibleElems();
var cardElems = viselems.Where(x => !(x is SchemaElemDetail)).ToList();
foreach (var elem in cardElems)
{
var value = (element.GetValue(elem.Name) ?? "").ToString();
if (!string.IsNullOrEmpty(value))
{
name_value.Add(elem.Name, value);
}
}
}
return name_value; //will be automatically serialised to JSON because of the dataType specification in ajax call.
}
You'd invoke this function in jQuery in ready like this :
$(document).ready(function () {
var schemaName = GetURLParameters('schemaName');
var key = GetURLParameters('key');
//just in case
var data = JSON.stringify({
name: schemaName,
keyN: key
});
$.ajax({
type: "POST",
url: "dataloader.aspx/getNameValue",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
var msg = JSON.parse(xhr.responseText);
alert(msg.Message);
}
}).done(function (msg) {
//msg.d will contain your dictionary
});
});
The reason its better to use this method is that code becomes reusable. In your current set up, if you want to get the name_value dictionary you'd have to reload the aspx page. Now all you need to do is call this method.
Hope this helps!

It's best to convert to JSON from the DataLoader.aspx page. Then, add a callback in the code segment above:
$.post("dataloader.aspx", {
name: schemaName,
key: key,
success: function(d) { .. }
});
The variable "d" contains the response, which would probably be string. You can then use JQuery in the same way to send the data to the next page, either by using JSON.parse and parsing the content, or by passing JSON directly.

In order to create the JSON you want, you are going to need to serialize your dictionary. You can use System.Web.Script.Serialization.JavaScriptSerializer:
var JSSerializer = new JavaScriptSerializer();
Response.Write(JSSerializer.Serialize(name_value));
Then in your JS code:
$(document).ready(function () {
var schemaName = GetURLParameters('schemaName');
var key = GetURLParameters('key');
$.post("dataloader.aspx", {
name: schemaName,
key: key
}, function(data){
//Here is your success callback and data should be your JSON.
});
});
To make this cleaner you might want to consider using an HTTP handler template (.ashx) instead of an .aspx page so you won't have all the over head of an aspx page (i.e. code-behind and view).

Related

Null parameter in Json controller method while Jquery parameter has value

I am creating a cascading dropdown list based on an example I found here
The query sent to the server to request the second dropdownlist values has non null parameters but when I break in the controller method, it appears empty. As you can see below.
Any help would be greatly appreciated ! Thanks !!
It's using jQuery and ASP.NET MVC 5 while my project is ASP.NET MVC Core 2
The code in the controller is the following :
public JsonResult States(string Country)
{
List<string> StatesList = new List<string>();
switch (Country)
{
case "India":
StatesList.Add("New Delhi");
StatesList.Add("Mumbai");
StatesList.Add("Kolkata");
StatesList.Add("Chennai");
break;
}
return Json(StatesList);
}
And here is the AJAX :
<script src = "/lib/jquery/dist/jquery.js" > </script>
<script>
$(document).ready(function ()
{
$("#State").prop("disabled", true);
$("#Country").change(function ()
{
if ($("#Country").val() != "Select")
{
var CountryOptions = {};
CountryOptions.url = "/Dropdown/states";
CountryOptions.type = "POST";
CountryOptions.data = JSON.stringify({ Country: $("#Country").val() });
CountryOptions.datatype = "json";
CountryOptions.contentType = "application/json";
CountryOptions.success = function (StatesList)
{
$("#State").empty();
for (var i = 0; i < StatesList.length; i++)
{
$("#State").append("<option>" + StatesList[i] + "</option>");
}
$("#State").prop("disabled", false);
};
CountryOptions.error = function ()
{
alert("Error in Getting States!!");
};
$.ajax(CountryOptions);
}
else
{
$("#State").empty();
$("#State").prop("disabled", true);
}
});
});
Since you have specified the contentType = "application/json" and are sending stringified data, then you need to add the [FromBody] attribute in the POST method to instruct the ModelBinder to use the content-type header to determine the IInputFormatter to use for reading the request (which for json is the JsonInputFormatter). Change the signature of the method to
[HttpPost]
public JsonResult States([FromBody]string Country)
However, it is not necessary send the data as json, and you can use the default contentType ('application/x-www-form-urlencoded; charset=UTF-8'). You can delete the contentType option and use
CountryOptions.data = { Country: $("#Country").val() }; // not stringified
// CountryOptions.contentType = "application/json";
For more information, refer Model binding JSON POSTs in ASP.NET Core.

AJAX Return object contains d in asp.net web form

Hey guys Its a simple question but want to stop ajax return object contains d.
I asp.net web form
$.ajax({
type: "POST",
url: myurl,
data: JSON.stringify({value:"1"}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//alert("i am in success");
console.log(result);
},
failure: function (response) {
console.log("I am in failure");
}
});
and
in .cs file
[WebMethod]
public static string getSpareParts(string value)
{
List<data> spareParts;
using (var db = new WaltonCrmEntities())
{
spareParts = db.SpareParts.Select(x => new data
{
id = x.ItemID,
text = x.ItemName
}).ToList();
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(spareParts);
//return spareParts;
}
when result is return it will contain result in result.d but i want to stop this d thing .Simply result should be the result. Can anybody solve this.
There's not much you could do about this. That's the way ASP.NET WebMethods always serialize the response. The reason why Microsoft decided to wrap the response in this .d property is to protect against this particular JSON hijacking vulnerability. Of course you could always check in your success callback whether this property is present or not:
success: function (result) {
var data = result.hasOwnProperty('d') ? result.d : result;
console.log(data);
}
Also I would very strongly recommend against writing plumbing code in your WebMethod (like serialization stuff) and just return the proper object and let the infrastructure care about serialization:
[WebMethod]
public static List<data> getSpareParts(string value)
{
using (var db = new WaltonCrmEntities())
{
return db.SpareParts.Select(x => new data
{
id = x.ItemID,
text = x.ItemName
}).ToList();
}
}
Now inside your success callback you can directly work with this collection without the need to additionally JSON.parse it:
success: function (result) {
var data = result.hasOwnProperty('d') ? result.d : result;
for (var i = 0; i < data.length; i++) {
console.log('id: ' + data[i].id + ', text: ' + data[i].text);
}
}

Getting JSON Object from MVC Controller

What I want is to protect my developer key while making an Ajax call to a cross-domain. Before I would just go straight to the url and plug in my key. Like this
$.ajax({
url: "https://na.api.pvp.net/api/lol/na/v2.3/team/TEAM-ID?api_key=mykey",
type: "GET",
data: {},
success: function (json) {
console.log(json);
console.log(json[teamID].name);
console.log(json[teamID].fullId);
console.log(json[teamID].roster.ownerId);
console.log(json[teamID].tag);
},
error: function (error) {}
});
This would give me the following Object, which I could easily parse out.
However, as mentioned, any person could easily grab my key during this process. So I decided to move this action to my Controller (yes I know there shouldn't be business logic here, but it is more secure and this is a quick process).
So what I am doing now is running my Javascript, which calls the Controller for a Json return.
Javascript
$.ajax({
url: "/Competitive/teamLookUp",
type: "POST",
data: "ID=" + teamID,
success: function (json) {
console.log(json);
},
error: function(error) {
}
});
And my Controller takes that in and attempts to return the JSON.
[HttpPost]
public ActionResult teamLookUp(string ID)
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://na.api.pvp.net/api/lol/na/v2.3/team/" + ID + "?api_key=myKey");
myReq.ContentType = "application/json";
var response = (HttpWebResponse)myReq.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
return Json(new { json = text });
}
However during this processs I return a string that is not a JSON object, thus cannot be parsed by my script.
It returns the entire json as one long string.
At this point I tried to add the following to my Controller.
var json2 = JsonConvert.DeserializeObject(text);
return Json(new { json = json2 });
But all that returned was some empty Object.
I have been trial and error'ing, searching, and guessing for the past 4 hours. I have no idea what to try anymore. I just want my Controller to pass back an Object that can be readable again like this. (Or at least some sort of formatted json object)
$.ajax({
url: "/Competitive/teamLookUp",
type: "POST",
data: "ID=" + teamID,
success: function (json) {
console.log(json);
console.log(json[teamID].name);
console.log(json[teamID].fullId);
console.log(json[teamID].roster.ownerId);
console.log(json[teamID].tag);
},
error: function (error) {}
});
Your method doesn't appear to need to be a POST as it is just getting data rather than modifying it. Therefore you could set it to be a GET instead.
Example
[HttpGet]
public JsonResult teamLookUp(string ID)
{
// Your code
return Json(text, JsonRequestBehavior.AllowGet);
}
Here's an excerpt from your code:
[HttpPost]
public ActionResult teamLookUp(string ID)
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://na.api.pvp.net/api/lol/na/v2.3/team/" + ID + "?api_key=myKey");
myReq.ContentType = "application/json";
// here's how to set response content type:
Response.ContentType = "application/json"; // that's all
var response = (HttpWebResponse)myReq.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
return Json(new { json = text }); // HERE'S THE ERRING LINE
}
Based on the response you received, I could understand that text already contains you desired JSON.
Now replace return Json(new { json = text }); with Json(text); and that should fix it.
To answer your question in the comments, here's how you can read the response data:
$.ajax({
url: "/Competitive/teamLookUp",
type: "POST",
data: "ID=" + teamID,
dataType: "json", // type of data you're expecting from response
success: function (json) {
console.log(json);
console.log(json[teamID].name);
console.log(json[teamID].fullId);
console.log(json[teamID].roster.ownerId);
console.log(json[teamID].tag);
},
error: function (error) {}
});
I think the problem lies where you say return Json(new {json = text;}). That's telling the json serializer to dump all your data into a property in the json obect called 'json', which is what you're seeing in the response.
Try return Json(text) instead.
Ending up using WebClient
[HttpPost]
public ActionResult teamLookUp(string ID)
{
string text = "";
try
{
using (var webClient = new System.Net.WebClient())
{
webClient.Encoding = Encoding.UTF8;
var json2 = webClient.DownloadString("https://na.api.pvp.net/api/lol/na/v2.3/team/" + ID + "?api_key=myKey");
return Json(json2);
}
}
catch (Exception e)
{
text = "error";
}
return Json(new { json = text });
}
And I parsed it like normal,
$.ajax({
url: "/Competitive/teamLookUp",
type: "POST",
data: "ID=" + ID,
dataType: "json",
success: function (resp) {
if (resp["json"] == "error") {
// error reaching server
} else {
// successfully reached server
}
json = JSON && JSON.parse(resp) || $.parseJSON(resp);
var userID = ID;
teamName = json[userID].name;
teamID = json[userID].fullId;
teamCPT = json[userID].roster.ownerId;
teamTag = json[userID].tag;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// error
}
});
I was having the same issue as the original poster: the ReadToEnd() call result escapes special characters and thus doesn't look like JSON to the receiving end, but then I saw a similar question answered here and thought others reading this might find it helpful as well.
To summarize: Deserializing in the Controller which the original poster tried was key, but also as others have pointed out, the return doesn't need the new {} call.
So pieced together:
using (var sr = new StreamReader(endpointResponse.GetResponseStream())) {
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
return Json(jsonObject, JsonRequestBehavior.AllowGet);
}

do I need getJson at all?

$(document).ready(function ()
{
$(".viewmap").click(function ()
{
var id = $(this).attr("id");
var responseURL = "~/changemap?id=" + id;
//alert(responseURL);
$.ajax(
{
url: responseURL,
dataType: "json",
type:"GET",
success: function (dt)
{
initialize(dt.Latt, dt.Longt);
}
}
);
}
);
});
I use that script to make an ajax call to the page changemap.cshtml which does the following
#{
if(!IsPost)
{
if(!Request.QueryString["id"].IsEmpty()&&Request.QueryString["id"].IsInt())
{
var countryId=Request.QueryString["id"];
var db=Database.Open("GoogleMapView");
var dbCmd="SELECT * FROM places WHERE id=#0";
var row=db.QuerySingle(dbCmd,countryId);
if(null!=row)
{
Json.Write(row,Response.Output);
}
}
}
}
That is to return the queried data from the database in json format to the client. The Initialize function is defined as
function initialize(lat,lng)
{
var mapOptions = {
center: new google.maps.LatLng(lat,lng),zoom: 8,mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("gmap"),mapOptions);
}
But when I click the div tag of class viewmap, nothing happens. I think I miss some more script to get my application to work correctly.
I only try to implement a simple google map view in which once the user clicks a place name as a hyperlink will reload the map that matches with it.
I think
var responseURL = "~/changemap?id=" + id;
should be
var responseURL = '#(Url.Content("~/changemap")+"?id=")' + id;
try thr following
success(data){
initialize(data.d.Latt, data.d.Longt);
}
for more reference as in why d is used check the following link
http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/

accessing the parameters of a JSON call in the web method

I don't need anything fancy or complex, I'm just trying to pass a simple string across as a parameter to my web method. How can I do it?
Here is the web method call
[WebMethod]
public static ArrayList GetColumns(string TorVName)
here is the JSON call:
<script type="text/javascript" language="javascript">
var qs = new Querystring();
var v1 = qs.get("TorVName");
var jsonData = JSON.stringify(v1);
$().ready(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetColumns",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var optString = '<option value="-1">Select Column</option>';
$.each(msg.d, function(index, item) {
optString += '<option value="' + item + '">' + item + '</option>';
});
$('select[name^=DDLColumns]').html(optString);
},
error: function() {
alert("Failed to load columns");
}
});
});
</script>
Here is the essence of my web method:
public static ArrayList GetColumns(string TorVName)
{
String cnstr = "myconnectstring";
//string TorVName = System.Web.HttpContext.Current.Request.QueryString["TableOrViewName"];
//string TorVName = "Aged";
//JavaScriptSerializer serializer = new JavaScriptSerializer();
string TorVName = System.Web.HttpContext.Current.Request.QueryString["TOrVName"].ToString();
string Sql = String.Empty;
I think its stupid and disheartening that this needs to be so complex and difficult.
Thanks Dean
In your ajax request, for the data parameter, do it like this:
data: "myData=" + jsonData,
Then in your web method, match the argument to "myData" like this:
[WebMethod()]
public static ArrayList GetColumns(string myData)
{
.....Your code
}
Your web method is smart enough to match the parameter to the argument if the names are the same. Once you receive your string, then you can deserialize it and call your non-webmethod to instantiate your custom data object.
If I understand what you want you just need to append the query string to your url in your ajax call:
url: "Default.aspx/GetColumns?param=value",
I could not understand what you want exactly. Anyway from my point of view, I see you're using JQuery. I have written a JQuery plugin to call ajax methods easier. you can download it from: http://www.4shared.com/file/Y72VBeLc/PageMethod.html
Usage:
$.PageMethod('PageMethodName', successFunction, failFunction, 'param1', param1, 'param2', param2, ...);
An example:
Javascript:
var myName = 'TestName';
var myId = '123';
$.PageMethod('ReturnCustomData', onSuccess, onFail, 'MyName', myName,'MyID', myId);
Code Behind:
public class CustomData
{
public string name;
public int id;
}
[WebMethod()]
public static CustomData ReturnCustomData(string MyName, int MyID)
{
CustomData MyData = new CustomData();
MyData.name = MyName;
MyData.id = MyID;
return MyData;
}
The success function can have a serialized json object as a return value. in your callback function, you can access the CustomData
function onSuccess(response)
{
alert('Your Name: ' + response.d.name + ', Your ID: ' + response.d.id);
}
function onFail(response)
{
alert("An error occurred.");
}

Categories

Resources