My goal is to create a column highchart that shows the name of various salesman and how much they have sold. I wrote this code to return from my SQL Database the names and the sum of the sales for each salesman:
[HttpPost]
public JsonResult ChartVendedores()
{
//Retorna um JSON contendo o nome do vendedor e o valor por ele vendido, usando inner join pelo id do vendedor.
try
{
var resultado = (from ve in db.tblVendedor
join vn in db.tblVenda on ve.vendedor_id equals vn.vendedor_id
group vn by new
{
ve.vendedor_nome
}into g
select new {
vendedor_nome = g.Key.vendedor_nome,
venda_valor = g.Sum(x => x.venda_valor)
}).ToList();
var jsonResult = new
{
Nomes = resultado.Select(x => x.vendedor_nome),
Valores = resultado.Select(x => x.venda_valor)
};
return Json(resultado);
}catch(Exception)
{
return null;
}
}
And this is where the chart is created, the method is called and it is suposed to fill the chart with the database's return data:
<script>
$(function () {
$.ajax({
url: '/Vendedores/ChartVendedores',
type: 'post',
async: false,
sucess: function (data) {
//Constrói o gráfico com os valores retornados pelo banco.
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Venda dos Colaboradores'
},
xAxis: {
categories: [
data.Nomes
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Valor (R$)'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Valores',
data: data.Valores
}]
});
}
})
})
What am I'm missing? As long as code goes, i don't think I wrote any wrong code in the method. Am I calling it wrong? Am I manipulating it wrong? I tried to remove my Ajax code, only leaving the chart itself as it is on the highchart.com and it worked, so the problem is not on my container div or in the chart code.
EDIT: As commented bellow, I looked at my console and I'm getting an warning about one of the imports that Highcharts needs. The waning follows is this one. After seeing this, I tried to remove the AJax and only using the highchart code. It worked! For some reason when the chart tries to use this:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
It does not find it when the chart code is contained inside sucess: function(data){}
Note: I'm importing everything at the beggining of the code, meanwhile the script containing the Ajax is written last.
$.ajax({
url: '/Vendedores/ChartVendedores',
type: 'post',
async: false,
sucess: function (data) {
should be changed to:
$.ajax({
url: '/Vendedores/ChartVendedores',
type: 'post',
async: false,
success: function (data) {
You have misspelt success.
look at this, you are using return(resultado), but your json object to be returned is jsonResult , so use this:
var resultado = (from ve in db.tblVendedor
join vn in db.tblVenda on ve.vendedor_id equals vn.vendedor_id
group vn by new
{
ve.vendedor_nome
}into g
select new {
vendedor_nome = g.Key.vendedor_nome,
venda_valor = g.Sum(x => x.venda_valor)
}).ToList();
var jsonResult = new
{
Nomes = resultado.Select(x => x.vendedor_nome),
Valores = resultado.Select(x => x.venda_valor)
};
return Json(jsonResult);
Please test and let me know if it works :)
for (var i in data) {
// Add some text to the new cells:
cell1.innerHTML = data[i].Nomes ;
cell2.innerHTML = data[i].Valores ;
}
Related
I'm using EF6 + MVC for a site. The dataTables editor is used for an UI. One table has a field 'StartDate'. It is a datetime type in the SQL Server.
It works fine until when I try to edit the 'StartDate' value. From the browser debug, I can see that the JSON send from backend to UI is in the timestamp format, i.e. /Date(1541923200000)/ .
In the dataTables, I convert this to the correct local datetime format, so it shows correctly.
However, I could not figure out how to do this in Editor plugin. It always shows the /Date(1541923200000)/ .
The code I use is:
editorAdvertisement = new $.fn.dataTable.Editor({
ajax: '/APN/GetAdvertisementData',
table: "#tblAdvertisements",
fields: [{
label: "StartDate",
name: "AdvStartDate"
, type: "datetime"
, format: 'MM\/DD\/YYYY h:mm a'
}, {
label: "Deadline",
name: "AdvDeadline"
, type: "datetime"
}, {
label: "TitleOfAdv",
name: "TitleOfAdv"
}, {
label: "ListPrice",
name: "ListPrice"
}
]
});
var tbl = $('#tblAdvertisements').DataTable({
pageLength: 10,
dom: '<"html5buttons"B>lTfgitp',
ajax: '/APN/GetAdvertisementData'
,
columns: [
{
data: "AdvStartDate", name: "AdvStartDate"
, type: "datetime"
, render: function (value) {
var r = convertDate(value);
return r;
}
, "autoWidth": true
},
{
data: "AdvDeadline", name: "AdvDeadline"
, type: "datetime"
, render: function (value) {
var r = convertDate(value);
return r;
}
, "autoWidth": true
},
{ data: "TitleOfAdv", name: "TitleOfAdv", "autoWidth": true },
{
data: "ListPrice", name: "ListPrice", "autoWidth": true
, render: $.fn.dataTable.render.number(',', '.', 0, '$')
}
],
order: [1, 'asc'],
select: {
style: 'os',
selector: 'td:first-child'
},
buttons: [
{ extend: "create", editor: editorAdvertisement }
, { extend: "edit", editor: editorAdvertisement }
, { extend: "remove", editor: editorAdvertisement }
]
, select: true
, searching: false
, paging: false
});
In the controller
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult GetAdvertisementData()
{
var request = HttpContext.Request.Form;
var settings = Properties.Settings.Default;
using (var db = new Database(settings.DbType, settings.DbConnection))
{
var response = new Editor(db, "Advertising", new[] { "AdvertisingID" })
.TryCatch(false)
.Model<Advertising2>()
.Field(new Field("AdvStartDate")
.Validator(Validation.DateFormat(
"MM/dd/yyyy",
new ValidationOpts { Message = "Please enter a date in the format MM/dd/yyyy" }
))
.GetFormatter(Format.DateTime("yyyy-MM-dd HH:mm:ss", "MM/dd/yyyy"))
.SetFormatter(Format.DateTime("MM/dd/yyyy", "yyyy-MM-dd HH:mm:ss"))
)
.Field(new Field("AdvDeadline")
.Validator(Validation.DateFormat(
"MM/dd/yyyy",
new ValidationOpts { Message = "Please enter a date in the format MM/dd/yyyy" }
))
.GetFormatter(Format.DateSqlToFormat("MM/dd/yyyy"))
.SetFormatter(Format.DateFormatToSql("MM/dd/yyyy"))
)
.Field(new Field("TitleOfAdv"))
.Field(new Field("ListPrice"))
.Process(request)
.Data();
return Json(response, JsonRequestBehavior.AllowGet);
}
}
I could not figure it out after a long search. Anyone had the same issue? Any solution?
Check Out moment.js (https://momentjs.com), download moment-with-locales.js and add it to your ScriptBundle in BundleConfig.cs.
Then in your datatable's javascript code you can render the column in proper date/time format as follows. Note: my locale is 'pt' (Portugal). The date column is rendered as dd/mm/yyyy hh:mm (once again, see the formatting options in https://momentjs.com).
"columns": [
{ "data": "OriginName" },
{ "data": "SmsID" },
{ "data": "DestinationNumber" },
{
"data": "SMSDeliveryDate",
"render": function (data) {
var re = /-?\d+/;
var m = re.exec(data);
var d = new Date(parseInt(m[0]));
moment.locale('pt');
var m = moment(d).format('L LTS');
return m;
}
},
{ "data": "SmsStateDesc" }
],
Hope this info can be useful. I too was stuck with this for a few hours...
José
I had the same problem and eventually found the answer on the Editor forum.
If you look with fiddler (a great tool for seeing what happens) you
see the JSON has this format you get. If you look in the code in
visual studio express and capture what you got before passing it to
JSON you see something like "{12/12/2012 12:12}". So actually the
cause is the JSON.
Refactoring to just the essentials in your first column it should read like this.
This approach solved my problem without any problem. This version is designed to render null dates as blanks, otherwise format as directed. (Update: refactored the answer again, seeing that the next morning the formatted codes were not behaving as expected.)
{
data: "AdvStartDate",
render: function (data, type, full) {
if (data != null) {
var dtStart = new Date(parseInt(data.substr(6)));
return dtStart.toLocaleDateString();
} else {
return "";
}
}
application in MVC fraework.
from list of employee grid when user click on Edit button particular employee data would get display in the page. i have added one autocomplete textbox for users
i want to set autocomplete value based on clicked employee data.
$("#autoAssginedTo").autocomplete({
source: function (request, response) {
$.ajax({
url: "/LeadGeneration/GetUsers",
type: "GET",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.FirstName + ' ' + item.LastName, value: item.FirstName + ' ' + item.LastName, val: item.ID };
}))
}
})
},
messages: {
noResults: "", results: ""
},
select: function (e, i) {
$("#AssignedTo").val(i.item.val);
},
});
i tried following :
function setAutocompletCurrentValue(id, value) {
$(id).val(value);
var textToShow = $(id).find(":selected").text();
$(id).parent().find("span").find("input").val(textToShow);
}
but it sets id of user. i want to set employee name associated with empId
how to do that ?
Instead of this:
$("#AssignedTo").val(i.item.val);
Replace it with this one:
$("#AssignedTo").val(i.item.label);
I have a view with a script (included below) that fires on a dropdownlist change, and the event handler should fill values for two text inputs. Values are received from controller.
The problem I'm having is, as soon as itemstatus list is populated, the controller returns back to view, and no values are passed back to AJAX function.
If I remove itemstatus list code and manually assign values as follows, it works:
var result = new { Quantity = "123", Price = "555"};
then it works.
I've also tried other ways to get data within controller but results were the same. Do you have any ideas what am I doing wrong and why controller returns back to view before "return Json"
<script type="text/javascript">
$(document).ready(function() {
//Dropdownlist Selectedchange event
$("#dropdown1").change(function ()
{
$("#txtQuantity").empty();
$("#txtPrice").empty();
$.ajax(
{
type: 'POST',
url: '#Url.Action("GetValues")',
dataType: 'json',
data: { id: $("#dropdown1").val() },
success: function(data)
{
$("#txtQuantity").val(data.Quantity);
$("#txtPrice").val(data.Price);
}
})
})
});
Controller:
public JsonResult GetValues(int id)
{
List<Item> itemstatus =
(from pd in db.Item
where (pd.itemID == id)
select new Item()
{
itemPrice = pd.itemPrice,
itemQuantity = pd.itemQuantity
}).ToList();
...
more code where i select what i need as a result i have two strings named itemquantity and itemprice
...
var result = new { Quantity= itemquantity, Price = itemprice };
return Json(result, JsonRequestBehavior.AllowGet);
}
because you are sending a list, whose data values can be accessed using
success: function(data)
{
$("#txtQuantity").val(data[0].Quantity);
$("#txtPrice").val(data[0].Price);
}
i have to create auto complete text box in my web form for the below condition
if i type country name then the auto complete suggestion should show the list of countries,state and city name which are stored in my database.
if i type city name then the auto suggestion should show the country and statename from my database,similarly statename also
For Example : if the user type
tamilnadu
then the result will be
tamilnadu, India
if the user type chennai in text box
then the auto complete suggestion should be
chennai,tamilnadu, india
if the user type Erode tamilnadu
then the result should be
Erode,tamilnadu,india
i have use different tables for each values like city, state, and country
all i have done till now is ive a textbox which shows only city search
My question is how can i achieve the result as i mentioned above like mulitple entries input to the textbox and multiple suggestion as a output like google place search
pls guide me i've search all over the web but i cant find the perfect solution
Here is my code for script
<script type ="text/javascript" >
$(function () {
$('#<%=txtSearch.ClientID%>').autocomplete({
source: function (request, response) {
$.ajax({
url: "Default.aspx\getCityName",
data: "{'pre':'" + request.term + "'} ",
datatype: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
cityname: item.cityname,
country: item.country,
json: item
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
focus: function (event, ui) {
$('#<%=txtSearch.ClientID%>').val(ui.item.cityname);
return false;
},
select: function (event, ui) {
$('#<%=txtSearch.ClientID%>').val(ui.item.citycame);
return false;
}
}).data("ui.autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>City:" + item.cityname + "<br>Country :" + item.country + "</a>")
.appendTo(ul);
};
});
</script>
Code of my webservice :
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Searchcity> getCityName(String pre)
{
List<Searchcity> allcity = new List<Searchcity>();
using(MydatabaseEntities dc = new MydatabaseEntities())
{
allcity = (from a in dc.Searchcities
where a.cityname.StartsWith(pre)
select a).ToList();
}
return allcity;
}
This may help you!
AJAX
var Autoarr = [];
$.ajax({
url: "',
dataType: "json",
async: false,
success: function (data) {
var result = $.map(data, function (val, key) {
return { type: key, cityname: val.cityname, country: val.country};
});
for (var i = 0; i < result.length; i++) {
Autoarr[i] = result[i].cityname;
}
}
});
AUTOCOMPLETE
$(function () {
$("#category").autocomplete({
source: Autoarr
});
});
You have to write SQL query with selection of 3 coloumns. 1> Country 2> State 3> City. SQL query should have 3 conditions.
Like below
if(select count(1) from Table where cityname like "#cityname")
begin
select city,state,country from table
end
else if(select count(1) from Table where state like "#statename")
begin
select 1 as city, state,country from table
end
else if(select count(1) from Table where country like "#countryname")
begin
select 1 as city, 1 as state, country from table
end
Please get this value in json using ajax.
Then append every each column with ',' seperator for example(Chennai,Tamilnadu,India).
If any coloumn value is 1 then omit it. for example
(1,Tamilnadu,India then omit 1. so Tamilnadu,India). You need to think more with this example. If you have different tables then use joins.
I have created one string array in jquery of name array[] and pushed values to it.
How can I send this array in query string?
For example window.location.href('ViewData?array');
And how can I get back the array data from query string in jquery itself ?
Please advice?
This is very easy to achieve with jQuery as it has a helper function called param().
var myData = {
name: "John Doe",
age: 23,
children: [{
name: "Jane Doe",
age: 13,
children: []
},
{
name: "John Doe Jr.",
age: 16,
children: []
}
],
}
var p = $.param(myData)
The results:
"name=John+Doe&age=23&children%5B0%5D%5Bname%5D=Jane+Doe&children%5B0%5D%5Bage%5D=13&children%5B1%5D%5Bname%5D=John+Doe+Jr.&children%5B1%5D%5Bage%5D=16"
You can use it like so:
window.location = "/MyController/MyAction?" + p;
As for getting parameters from query strings, please refer to the following question: How can I get query string values in JavaScript?
Another thing you can do is use an ajax call, this way you don't have to serialize the data yourself as it is done for you automatically.
$.ajax({
url: "/MyController/MyAction",
data: myData,
dataType: "json",
type: "POST",
success: function(data){
//'data' is your response data from the Action in form of a javascript object
}
})
I think this is what you are looking for. Let me know if I get it wrong. I copied $.parseParams from this link. You can also see working code here
(function($) {
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
var params = {}, e;
while ( e = re.exec(query) ) {
var k = decode( e[1] ), v = decode( e[2] );
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
return params;
};
})(jQuery);
var s=["abc", "xyz", "123"];
var queryString=$.param({a:s});
console.log("object to query string: ", queryString);
console.log("query string to object: ", $.parseParams(queryString));