asp.net mvc 3 highchart - c#

In addition to my previous question, I tried to use the same working code (for MVC2) in a MVC3 project. I figured out it's not possible to use the jQuery.getJSON method. So I tried to use the $.post and $.ajax method instead, but again facing a problem.
In both methods I get an error "Jscript: JB is empty or not an object"
$.post("Home/GetLineData", null, function (items) {
var series = [];
jQuery.each(items, function (itemNo, item) {
//Get the items from the JSON and add then
//to the data array of the series
series.push({
name: item.Key,
data: item.Value
})
});
options.series = series;
chart = new Highcharts.Chart(options);
chart.render();
});
$.ajax({
type: "POST",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
url: "/Home/GetLineData",
cache: false,
succes: function (data) {
var series = [];
jQuery.each(data, function (itemNo, item) {
//Get the items from the JSON and add then
//to the data array of the series
series.push({
name: item.Key,
data: item.Value
})
});
options.series = series;
//Create the chart
chart = new Highcharts.Chart(options);
chart.render();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
Thanks in advance for helping me out (again :-s).

The problem was in the HTML, so the container element was not found.
So now both methods are working!
Jorelie.

BTW - you can use getJSON in MVC 3.0, but your controller method has to return the JSON object with a second parameter like so :
Json(result, JsonRequestBehavior.AllowGet);

Related

Passing array from view to controller using Ajax but, on action, array shows as empty

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");
}
});

Pass array to Controller Action via AJAX

I saw similar questions, but none helps me.
I have the simplest code:
public JsonResult JsonGetStatesInfo(object[] instructions)
{
if (Request.IsAjaxRequest())
{
return Json(String.Empty);
}
else
throw new NoAjaxRequestException();
}
and client side:
var instructions = [];
instructions.push('abc');
instructions.push('ddd');
instructions.push('assdbc');
var inst = JSON.stringify(instructions);
$.ajax({
cache: false,
data: { 'instructions': inst },
traditional: true,
dataType: 'json',
url: '/State/JsonGetStatesInfo',
type: 'post',
success: function (resp) {
},
error: function (data) {
alert(data.error);
}
});
On client side I tried with JSON.stringify, without JSON.stringify, with traditional: true, without traditional: true
On server side I tried as parameter : object[], object, List< object >, List< string >, IEnumerable< string > etc
Nothing worked! How to do it correctly?
SOLVED:
My problem was trivial - one from real values of array had HTML Tag. Just need add [ValidateInput(false)] to action method
You just need the following settings:
Pass array of string to a MVC Action by Ajax:
Controller:
public JsonResult MyAction(string[] instructions)
{
// Your codes
}
View:
$.ajax({
data: { 'instructions': ['abc', 'dcs', 'arr'] }, // << Without JSON.stringify
traditional: true, // << Important line
url: '/State/MyAction',
type: 'post',
dataType: 'json',
success: function (resp) {
// Your codes
}
});
Using contentType: "application/json; charset=utf-8" is recommended too.
Pass array of int to a MVC Action by Ajax:
Also I use bellow codes to path an array of int to an Action
Controller:
public JsonResult MyAction(int[] instructions)
{
// Your codes
}
View:
$.ajax({
data: { 'instructions': [1, 2, 3] }, // << Without JSON.stringify
traditional: true, // << Important line
url: '/State/MyAction',
type: 'get',
dataType: 'json',
success: function (resp) {
// Your codes
}
});
public ActionResult JsonGetStatesInfo(string[] instructions)
{
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { result = instructions.Length}
};
}
Client side
var instructions = ['abc', 'dcs', 'arr'];
$.post('/State/JsonGetStatesInfo', { instructions: instructions },
function (data) {
if (data.result!= null && data.result!= undefined) {
alert(data.result);
}
});
Try this...
At least, you can pass javascript array as a string and deserialize it in the controller
public JsonResult JsonGetStatesInfo(string instructions)
var instructionsArray= JsonConvert.DeserializeObject<string[]>(instructions);
Or use new Array like explained here : https://stackoverflow.com/a/310136/3063094
Try adding:
contentType: "application/json; charset=utf-8"
To you AJAX call, And please delete the:
JSON.stringify(instructions);
Because you are trying to stringify an object, which will be sent to the server as a string rather than an object (and the server side expects an object).
you can also delete the
traditional: true,
ache: false,

Auto Complete in Razor MVC.NET [duplicate]

I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx

Object obect error on jquery ajax request on dropdown change?

I'm using jquery ajax on dropdown change function.The problem is that even before hitting the url mentioned in the ajax request I'm getting Object object error.
The ajax request is as follows
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: "{ 'Location': '" + locationNo + "'}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
The server side code is as follows
[WebMethod]
public static string GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sjson=jSearializer.Serialize(lstCashSafeSelect);
return sjson;
}
I've checked the string sjson and the data is returning correctly in json format.
Since the error is showing even before the url is hit,i'm confused on how to proceed further.
Any help will be appreciated.
Change the data like this
data: JSON.stringify({ 'Location': locationNo }),
Then your code will look like
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: JSON.stringify({ 'Location': locationNo }),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
Edit
Since your dataType is json, you should return json, not string. Change your server side code like this,
[WebMethod]
public static List<CashSafeSelect> GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
return lstCashSafeSelect;
}
You dont have to serialize those lists
Issue solved,Thanks to every one who replied especially #Anoop.
Issue was that I've set Autopostback=true for the dropdown where the ajax call is made.I've removed the autopostback property of the dropdown and now the code is working fine.
I wonder how a fresh day,clear mind helps to solve the issues.

Posting list of object to controller, not MVC

First of all, I'm not using MVC but only it's routing and controller (in order to create RESTful API). I'm using c# web form
The problem that I have is posting list of object using AJAX post to my api controllers. I've read several examples and tried their example to no anvil =( one of the example that I tried is this:
Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
and
MVC Send list through AJAX
the data that I get is null, even I tried adding traditional: true in AJAX, still has no luck.
Maybe someone can give me some insight. Here's my code:
javascript:
var data = { warehouseProduct: [] };
data.warehouseProduct.push({
PID: 2,
PIDN: 'ABC',
CName: 'Toy',
EName: 'AKE-14',
Qty: 4,
});
$.ajax({
url: "/api/warehouse/PostUpdateData",
type: "POST",
contentType: 'application/json; charset=utf-8',
async: false,
dataType: "json",
traditional: true,
data: JSON.stringify(data),
error: function (xhr, ajaxOptions, thrownError)
{
alert(thrownError);
}
}).done(function (msg)
{
});
here's the code in the controller:
public string PostUpdateData(List<Warehouse> warehouseProduct)
{
// do something here
return "";
}
You wrapped the list of Warehouses in an object. You instead want to post just the array of Warehouses.
Try this:
var data = [];
data.push({
PID: 2,
PIDN: 'ABC',
CName: 'Toy',
EName: 'AKE-14',
Qty: 4,
});

Categories