I am using .NET MVC4
I have used javascript function as below:
function ShowDomainComponentDetail(compCode) {
alert(compCode);
$.ajax({
url: "/PP/getDomainComponentDetailWithDomain",
data: {
'ComponentCode': compCode
},
dataType: "json",
type: 'POST',
cache: false,
success: function (_responseData) {
$('#divShowDomainCompDetail').show();
alert(_responseData.Data)
},
error: function () {
//
}
});
}
Upon success I am getting list in .net as:
IdObservation=1, ObservationName="Started" , ObsType="Announced";
IdObservation=2, ObservationName="Not Started" , ObsType="Un Announced";
IdObservation=3, ObservationName="Declared" , ObsType="Announced";
My problem is i am not abl;e to access this list inside Ajax sucess block.
How can i access this list as:
alert(_responseData.IdObservation);
alert(_responseData.ObservationName);
(Further i am going to assign this to labels).
Please help me.
EDIT 1 :
My Serverside Function returning list:
public JsonResult getDomainComponentDetailWithDomain(string ComponentCode)
{
try
{
List<TEAMS_PP.Entity.correlations> compDetail_list = new correlation().getDomainComponentDetailswithDomain(ComponentCode);
return Json(compDetail_list);
}
catch (Exception)
{
List<TEAMS_PP.Entity.correlations> BlankList = new List<TEAMS_PP.Entity.correlations>();
return Json(BlankList);
}
}
Use index with data object like below:
alert(_responseData[0].IdObservation);
loop through object and get values for each object.
you can use the $each to iterate it
$.each(_responseData, function (key, value) {
var arr = value.IdObservation;
});
Related
I am passing an array from view to controller using Ajax but, on action, the array shows empty.
This is my code:
View
$("#btn").click(function () {
debugger
arry = [];
$.ajax({
type: "Post",
url: "/Main/CheckBoxes",
data: { Values: arr["48","47","46"] },
success: function () {
alert("array: " + arry.join(', '));
},
error: function () {
alert("error");
}
})
});
Action
public ActionResult array(string[] Values)
{
for (int id = 0; id < Values.Length; id++)
{
string newID = Values[id];
}
return View();
}
jQuery.ajaxSettings.traditional = true;
$("#btn").click(function () {
debugger
arry = [];
$.ajax({
type: "Post",
url: "/Main/CheckBoxes",
data: { Values:["48","47","46"]},//just edit this line
success: function () {
alert("array: " + arry.join(', '));
},
error: function () {
alert("error");
}
})
});
Your code has some issues regarding how you are sending the data! What is your expectation when you execute this expression arr["48","47","46"] ????? That is going to give you undefined and that is what you are trying to send!
There are two ways to fix your code. You can send the array in the request body. For this, you need create a JSON string from the array and send that as the data property while explicitly specifying the request content-type header value as "application/json". You may use the JSON.stringify method to get the JSON string of your js array.
Also, make sure you are making the call to the correct action method. In your question you shared the array action method code, but in your client side script you were trying to call a different action method(`Checkboxes)!
This should work.
var arry = ["48", "47", "46"];
var url = "#Url.Action("array", "Main")"; // Update your real url here
// If your script is inside the razor view, you can us Url.Action (c#) method
$.ajax({
type: "Post",
url: url ,
data: JSON.stringify(arry),
contentType: "application/json",
success: function(r) {
alert("Success");
console.log(r);
},
error: function() {
alert("error");
}
});
Another option is to send a javascript object with Values property (which has the array as the value of it) as the data property value of the $.ajax call. Now the request content-type header will be application/x-www-form-urlencoded; and the array will be sent as FormData in the request.
var arry = ["48", "47", "46"];
$.ajax({
type: "Post",
url: "/Main/array",
data: { Values: arry },
success: function(r) {
console.log(r);
},
error: function() {
alert("error");
}
});
I'm new in JQuery and AJAX. I tried to fill a DropDownList using AJAX in ASP.NET MVC 4 and it gives me this error:
The ObjectContext instance has been deleted and can not be used for operations that require a connection.
and here is my script:
function LoadFlights() {
var $flight = $('#IDFLIGHT');
$flight.empty();
$flight.append($('<option></option>').val('').html('Please Wait...'));
$.ajax({
url: '/Flight/GetFlightList',
type: 'POST',
data: {},
dataType: 'json',
success: function (d) {
$flight.empty();
$flight.append($('<option></option>').val('').html('Select Flight'));
$.each(d, function (i, val) {
$flight.append($('<option></option>').val(val.IDFLIGHT).html(val.DATEFLIGHT));
});
},
error: function () {
}
});
}
And this is the action in the controller Flight I call:
public JsonResult GetFlightList()
{
FlightService flightService = new FlightService();
var all = flightService.GetAll();
return new JsonResult { Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
The variable all has data but it still give me the error mentioned above.
Thank you
You should use return Json(all,JsonRequestBehavior.AllowGet);, just passing the list data to the constructor will not convert it to JSON object.
P.S. the funtion Json() will return JsonResult
This should be simple but I cannot seem to get this to work correctly.
Given a JSON string that looks like this:
{
"?xml":
{
"#version":"1.0",
"#encoding":"ISO-8859-1"
},
"results":
{
"title":"AOL Movies - Closest Theater and Showtimes",
// etc,
"theater":
{
"theaterId":"10650",
"id":"10650",
// etc
},
"movie":
[
{
"studios":"Warner Bros.",
"movieId":"61683"
}
]
}
I continually get undefined objects when trying to get to any value, for example:
data.movie, or data.results.title.
Everything "looks" ok in the output.
jQuery.ajax({
type: 'GET',
contentType: 'application/json',
url: 'handler.ashx',
data: 'zip=' + postalCodes.join(','),
success: function (payload) {
var data = that.objectifyJSON(payload); // this returns typeof = object
that.constructMoviesArray(data);
},
error: function (error) {
alert(error.responseText);
}
});
this.constructMoviesArray = function (data) {
var key, movie, theater = null;
var movies = {};
movies.items = {};
movies.length = 0;
alert(data[0].movie); // FAIL - there's clearly an array but nothing displays
I hope this is enough information; I am not experienced with JSON and jQuery so I'm struggling to figure out why I can't seem to resolve this.
Add the json dataType. http://api.jquery.com/jquery.ajax/
The server response is probably still a string even though you set the contentType.
jQuery.ajax({
type: 'GET',
contentType: 'application/json',
url: 'handler.ashx',
data: 'zip=' + postalCodes.join(','),
dataType: 'json', // <--- UPDATE ME
success: function (payload) {
var data = that.objectifyJSON(payload); // this returns typeof = object
that.constructMoviesArray(data);
},
error: function (error) {
alert(error.responseText);
}
});
If that doesn't help, try adding a console.log or a breakpoint to the success callback. You'll be able to take a closer look at what kind of data you are working with in payload.
success: function (payload) {
console.log(payload);
},
Hope that helps!
Try Like
var geocodingAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
$.getJSON(geocodingAPI, function (json) {
// Set the variables from the results array
var address = json.results[0].formatted_address;
console.log('Address : ', address);
var latitude = json.results[0].geometry.location.lat;
console.log('Latitude : ', latitude);
var longitude = json.results[0].geometry.location.lng;
console.log('Longitude : ', longitude);
// Set the table td text
$('#address').text(address);
$('#latitude').text(latitude);
$('#longitude').text(longitude);
});
Demo
Oh boy what did I get myself into this time. Have to get some KendoUI cascading dropdrown lists working properly but I figure I will start off with two for now. Basically I need to retrieve whatever the user chooses for the first list in the view and send that back to the controller then pass it to an Entity Framework method (which I already have setup). Here is what I have now. The controller then passes back the appropriate 2nd dropdown list based on the first dropdown division value selected. I have tried using the Kendo stringify(data) trick in the parametermap as well as using cascadeFrom: "division", as suggested in the kendoui docs but that hasnt worked so far. Thus leading me to this interesting creation so far.
Any help or Garfield Comics are greatly appreciated.
The JS for the dropdownlists;
var divisions = $("#division").kendoDropDownList({
optionLabel: "Select category...",
dataTextField: "CodeAndDescription",
dataValueField: "Code",
dataSource: {
// type: "odata",
serverFiltering: true,
transport: {
read: {
url: VIPApiUrl + "GetDivision",
dataType: "json",
async: false,
type: "POST",
}, parameterMap: function (options, type) {
// edit VARS passed to service here!
if (type === 'read') {
return {
'division': options.division,
// 'criteria[0].Value': options.value
// ...
};
}
}
}
},
change: function () {
var value = this.value();
alert(value);
if (value) {
itemGroupDataSource.one("change", function () {
itemGroup.current(null);
}).filter({
field: "ID",
operator: "eq",
value: parseInt(value)
});
itemGroup.enable();
} else {
itemGroup.enable(false);
}
itemGroup.select(0);
}
}).data("kendoDropDownList");
var itemGroupDataSource = new kendo.data.DataSource({
//type: "odata",
serverFiltering: true,
transport: {
read: {
url: VIPApiUrl + "GetItemGroup",
dataType: "json",
async: false,
type: "POST",
}
}
});I
My controller where I need to access the json:
#region GetItemGroup
[HttpPost]
public List<ItemGroupsDTO> GetItemGroup(JObject jsonData)
{
dynamic json = jsonData;
string x = null; //intentionally pass null values
string division = json.division;
List<ItemGroupsDTO> ItemGroups = new List<ItemGroupsDTO>();
var ItemGroupEOList = new VIPItemGroupBOList();
ItemGroupEOList.Load(x, x, division, x, x, x, x, x, x, x, false);
foreach (var d in ItemGroupEOList)
{
var ItemGroup = new ItemGroupsDTO();
ItemGroup.Code = d.Code;
ItemGroups.Add(ItemGroup);
}
return ItemGroups;
}
#endregion
Okay I fixed this by changing the parameter map in the itemGroupDataSource to:
parameterMap: function (options, operation) {
return {
division: options.filter.filters[0].value
}
}
and changed the value field to:
dataValueField: "CodeAndDescription",
So I am guessing I partly wasn't giving the EO the right information but hopefully this helps someone in a Jam.
I was looking on internet for over 2 hrs now, trying to find simple example of how to fill jQuery Variable from serverside code on load of asp.net page.
What i have so far:
I have a button which call this jquery code:
function GetListOfQuestions() {
$.ajax({
type: "POST",
url: 'UserProfile.aspx/getQuestions',
contentType: "application/json; charset=utf-8",
dataType: "json",
error: OnAjaxError,
success: AjaxSucceeded
});
//$.getJSON('UserProfile.aspx/getQuestions', {}, function (data) {
// alert(data);
//});
}
function AjaxSucceeded(result) {
alert(result);
}
GetListOfQuestions calls serverside :
[WebMethod]
public static List<Question> getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return list.ToList();
}
result return an object if I alert it, so it must contain some kind of data, but I can't find any example of how I can retrieve data again on client side.
I'm not sure if what I am doing right now is right at all (I'm new to jQuery). So how can I retrieve data from result variable again?
There could be better ways but this is one way I know of:
[WebMethod]
public static string getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return new JavaScriptSerializer().Serialize(list.ToList())
}
In your jQuery method, you can
result = $.parseJSON(data) ;
Do a console.log(result) to see how to iterate through result, should be just a for loop.
Put a hidden field on your page an set the variable value there, later read the hidden value from js.
Another option is to use ScriptManager.RegisterStart UpScript to write your variable directly as js to the page.