Jquery list passes values null in controller side [duplicate] - javascript

I want to pass list through AJAX. How can I do this and assign value on runtime. I am doing it, but it pass null value. Here is my code.
JQuery:
for (var i = 0; i < 5; i++) {
aabc += { id: i, color: 'Level' + i } + ",";
}
var str2 = aabc.replace(/,$/, " ")
JSONString3 = [str2];
$.ajax({
url: '#Url.Action("test123", "ConfigurableTradeLane")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(JSONString3),
success: function (data) {
//alert("success");
},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Controller:
public void test123(List<TradelaneDetailViewModel> viewmodel)
{
//nothing
}
It send "item value is null". Please help me.

Assuming TradelaneDetailViewModel contains properties id and color, then the script needs to be
var items = [];
for (var i = 0; i < 5; i++) {
items.push({ id: i, color: 'Level' + i });
}
$.ajax({
url: '#Url.Action("test123", "ConfigurableTradeLane")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ viewmodel: items }),
success: function (data) {
//alert("success");
},
error: function (jqXHR, exception) {
alert('Error message.');
}
});

Related

Morris Donut Graph: How to get label of element on click event

I am using Morris Donut chart and the following is my code:
$(document).ready(function () {
var data_dg = #Html.Raw(Json.Encode(Model))
donut_chart_data = [];
for (var i = 0; i < data_dg.length; i++) {
var iName = data_dg[i].ItemName;
var Cnt = data_dg[i].Count;
donut_chart_data[i] = {
label: iName,
value: Cnt
};
}
Morris.Donut({
element: 'donut-graph',
colors: ['#D3696C', '#db9b9d', '#f74c52', '#632527', '#a3304f', '#820202', '#6d4141'],
data: donut_chart_data
});
$("#donut-graph").click(function (i, row) {
var ItemName = 'Paper';
$.ajax({
type: "POST",
url: '/Home/GetDataByID',
contentType: "application/json; charset=utf-8",
data: '{ ItemName: "'+ItemName+'" }',
dataType: "json",
success: function (response) {
alert('success');
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
And as you see in the click event I am trying to send a parameter ItemName which currently is hard coded but I want to send the label of the element on which the user clicks as the parameter value.
row.label
gives you the label of the clicked Element

ajax send 2d array to action method error - asp.net mvc

i want to send 2d array from javascript file to action method.
My javascript function
function _tbdata() {
var dataarr = [];
for(var i = 0; i<svarr.length; i++)
{
var trangthai = $("input[name='" + svarr[i] + "']:checked").val();
var lydo = $("#" + svarr[i]).val();
dataarr[i] = new Array(2);
dataarr[i][0] = trangthai;
dataarr[i][1] = lydo;
}
$.ajax({
url: '/DiemDanh/testMethod',
data: { info: JSON.stringify(dataarr ) },
type: "POST",
traditional:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
And my controller
[HttpPost]
public ActionResult testMethod(List<List<string>> info)
{
return RedirectToAction("Index");
}
And when i debug in chrome, i got error
POST http://localhost:56602/DiemDanh/testMethod 500 (Internal Server
Error)
Sorry about my Enligsh is bad, Hope suggest from everybody!!!
I think you should change your javascript. Two dimensional array sholud be [[]]
I've write an example for your code. It works fine.
function Test() {
var dataarr = [[]];
for (var i = 0; i < 1; i++) {
dataarr[i][0] = "A" + i.toString();
dataarr[i][1] = "B" + i.toString();
}
var model = JSON.stringify(dataarr);
$.ajax({
url: '/Home/testMethod',
data: model,
type: "POST",
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
Change your ajax like this.
$.ajax({
url: '/DiemDanh/testMethod',
data: { info: JSON.stringify(ngay) },
type: "POST",
traditional:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
change your method parameter with string multi dimensional array it will work because list of list strings parameter won't work it'll not accepting 2d array
[HttpPost]
public ActionResult testMethod(string [][] info)
{
return RedirectToAction("Index");
}

how to use json data sent from backend

$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
<li>"i want to insert variable here"<li>
},
error: function (data) {
console.log('Error:', data);
}
});
controller returns this
return Response::json($results);
and it gives this
{"results":[{"id":1,"name":"user","nick":"user1"}]}
how can i acces this in ajax part
You can use the data in ajax, sent from controller like this:
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) { // <-------- here data is your variable having json received from backend
$.each(data.results, function(key, val) {
// Use your results array here...
$('li.data').each(function(i) {
$(this).find('span.id').text(val.id);
$(this).find('span.name').text(val.name);
$(this).find('span.nick').text(val.nick);
});
});
},
error: function (data) {
console.log('Error:', data);
}
});
You'll get json inside the data variable under the success section of your ajax call
Hope this helps!
In your success method you can access the data returned from the server as:
success: function(data) {
var users = data.results;
var temptale = '';
for (var i = users.length - 1; i >= 0; i--) {
temptale += "<li>Name - " + users[i]['name'] + "<li>"
}
// use temptale to insert in your DOM
},
var queryInfoById= function (id) {
var params = {
"id": id,
};
$.getJSON(prefix + "/queryById.do", params, function (data) {
$("#name").val(data.name);
$("#age").val(data.age);
});
};
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
var array = data.results;
for (var i=0; i < array.length; i++){
var obj = array[i];
var id = obj.id;
var name= obj.name;
var nick= obj.nick;
//Add here the data in your UL>LI elements.
}
},
error: function (data) {
console.log('Error:', data);
}
});

Fill Variable with Web Service Results

I have a javascript function that is executed onClick via jquery. Within this function I am calling a Web Service "getTestConnection" which returns a True or False and I have confirmed it is working but keeps returning variable undefined.
$("#btnNext2").click(function() {
var postData = {}; {
postData['user'] = user;
postData['password'] = password;
postData['serviceurl'] = serviceurl;
postData['datasource'] = datasource;
};
//Converts object to string and formats to JSON
var json = JSON.stringify(postData);
//connTest keeps getting returned as 'Undefined'
var connTest = getTestConnection(json);
});
< script type = "text/javascript" >
function getDocType(json, rowcount) {
$.ajax({
type: "POST",
url: "http://localhost:64580/Web_Services/WebServiceLibrary.asmx/GetDocTypes",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//*****************************************************************************
//This is being called immediately after getTestConnection is executed
//******************************************************************************
for (i = 0; i < data.d.length; i++) {
$('#SelectDocType' + rowcount + '')
.append($("<option></option>")
.attr("value", data.d[i].docTypeID)
.text(data.d[i].docTypeName));
}
var firstDocTypeID = data.d[0].docTypeID;
var jsonUnstringify = JSON.parse(json);
var postDataNew = {}; {
postDataNew['user'] = jsonUnstringify.user;
postDataNew['password'] = jsonUnstringify.password;
postDataNew['serviceurl'] = jsonUnstringify.serviceurl;
postDataNew['datasource'] = jsonUnstringify.datasource;
postDataNew['docTypeID'] = firstDocTypeID;
};
var jsonnew = JSON.stringify(postDataNew);
getKeywords(jsonnew, rowcount);
},
error: function(data) {
alert("***********Error***********" + data.responseText);
},
failure: function(data) {
alert("***********Failure***********" + data.responseText);
}
});
//Test Connection Web Service
function getTestConnection(json) {
$.ajax({
type: "POST",
url: "http://localhost:64580/Web_Services/WebServiceLibrary.asmx/TestConnection",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
if (data.d == 'True') {
return true;
} else {
return false;
}
},
error: function(data) {
alert("***********Error***********" + data.responseText);
},
failure: function(data) {
alert("***********Failure***********" + data.responseText);
}
});
}
< /script>
You have multiples errors:
You have a <script type = "text/javascript"> tag inside another <script> tag
You define a new function inside another function:
function getDocType(json, rowcount) {
$.ajax({
.....
});
function getTestConnection(json) {
....
}
}
which should be
function getDocType(json, rowcount) {
$.ajax({
.....
});
}
function getTestConnection(json) {
....
}
You forgot to get returned data from the AJAX call in your getTestConnection function :
$.ajax({
type: "POST",
url: "http://localhost...",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if (data.d == 'True') {
return true;
} else {
return false;
}
},
error: function(data) {
....
}
});

How to get a list from mvc controller to view using jquery ajax

I need to get a list from mvc controller to view using jquery ajax. how can i do that. this is my code. Its alerting error message.
In Controller
public class FoodController : Controller
{
[System.Web.Mvc.HttpPost]
public IList<Food> getFoodDetails(int userId)
{
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return (FoodList);
}
}
In view
function GetFoodDetails() {
debugger;
$.ajax({
type: "POST",
url: "Food/getFoodDetails",
data: '{userId:"' + Id + '"}',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('eror');
}
});
}
Why you use HttpPost for GET-method? And need return JsonResult.
public class FoodController : Controller
{
public JsonResult getFoodDetails(int userId)
{
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return Json (new{ FoodList = FoodList }, JsonRequestBehavior.AllowGet);
}
}
function GetFoodDetails() {
debugger;
$.ajax({
type: "GET",
url: "Food/getFoodDetails",
data: { userId: Id },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('eror');
}
});
}
you can do like this , return json data and print it
Read full tutorial : http://www.c-sharpcorner.com/UploadFile/3d39b4/rendering-a-partial-view-and-json-data-using-ajax-in-Asp-Net/
public JsonResult BooksByPublisherId(int id)
{
IEnumerable<BookModel> modelList = new List<BookModel>();
using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())
{
var books = context.BOOKs.Where(x => x.PublisherId == id).ToList();
modelList = books.Select(x =>
new BookModel()
{
Title = x.Title,
Author = x.Auther,
Year = x.Year,
Price = x.Price
});
}
return Json(modelList,JsonRequestBehavior.AllowGet);
}
javascript
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("BooksByPublisherId"))",
data: { "id": id },
success: function (data) {
var result = "";
booksDiv.html('');
$.each(data, function (id, book) {
result += '<b>Title : </b>' + book.Title + '<br/>' +
'<b> Author :</b>' + book.Author + '<br/>' +
'<b> Year :</b>' + book.Year + '<br/>' +
'<b> Price :</b>' + book.Price + '<hr/>';
});
booksDiv.html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve books.');
}
});
The reason why i am not getting the result was.. I forgot to add json2.js in the library
public class FoodController : Controller
{
[System.Web.Mvc.HttpGet]
public JsonResult getFoodDetails(int userId)
{
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return Json (FoodList, JsonRequestBehavior.AllowGet);
}
}
function GetFoodDetails() {
debugger;
$.ajax({
type: "GET",
url: "Food/getFoodDetails",
data: { userId: Id },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('eror');
}
});
}
Try This :
View :
[System.Web.Mvc.HttpGet]
public JsonResult getFoodDetails(int? userId)
{
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return Json (new { Flist = FoodList } , JsonRequestBehavior.AllowGet);
}
Controller :
function GetFoodDetails() {
debugger;
$.ajax({
type: "GET", // make it get request instead //
url: "Food/getFoodDetails",
data: { userId: Id },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('error');
}
});
}
Or if ajax request is creating problems then you can use $.getJSON as :
$.getJSON("Food/getFoodDetails", { userId: Id } , function( data ) {....});
$(document).ready(function () {
var data = new Array();
$.ajax({
url: "list",
type: "Get",
data: JSON.stringify(data),
dataType: 'json',
success: function (data) {
$.each(data, function (index) {
// alert("id= "+data[index].id+" name="+data[index].name);
$('#myTable tbody').append("<tr class='child'><td>" + data[index].id + "</td><td>" + data[index].name + "</td></tr>");
});
},
error: function (msg) { alert(msg); }
});
});
#Controller
public class StudentController
{
#Autowired
StudentService studentService;
#RequestMapping(value= "/list", method= RequestMethod.GET)
#ResponseBody
public List<Student> dispalyPage()
{
return studentService.getAllStudentList();
}
}

Categories

Resources