Kendo Grid Aggregate Sum Displaying always 0 - ajax

I have Combobox event that call ajax function to fill grid datasource.
i can see my grid correctly filled but aggregate Sum display always 0.
What can i do?
AJAX call
$.ajax({
url: '#Url.Action("CreaGrid3", "Sales")',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { bra: brand, mod: model, prj: project, ver: version, rel: release },
success: function (result) {
var grid = $("#Grid3").data("kendoGrid");
var dataSource = new kendo.data.DataSource({
data: result.Data
});
grid.setDataSource(dataSource);
grid.dataSource.read();
}
Here my view:
#(Html.Kendo().Grid<IndSudUI.Models.TabTemp3>()
.Name("Grid3")
.Columns(columns =>
{
columns.Bound(e => e.DESCRIZIONE);
columns.Bound(e => e.Totale)
.Format("{0:C3}")
.ClientFooterTemplate("Sum: #=sum#");
})
.Pageable()
.Sortable()
.Scrollable()
.Resizable(resize => resize.Columns(true))
.DataSource(dataSource => dataSource
.Ajax()
.Aggregates(a =>
{
a.Add(p => p.Totale).Sum();
})
.ServerOperation(false)
)
.Events(events => events.DataBound("onDataBound5"))
)
Here my Controller
I removed some parts of code that are not relevant
public JsonResult CreaGrid3([DataSourceRequest] DataSourceRequest request, string bra, string mod, string prj, string ver, string rel)
{
if (!String.IsNullOrEmpty(bra))
bra = bra.Trim();
if (!String.IsNullOrEmpty(mod))
mod = mod.Trim();
if (!String.IsNullOrEmpty(prj))
prj = prj.Trim();
if (!String.IsNullOrEmpty(ver))
ver = ver.Trim();
if (!String.IsNullOrEmpty(rel))
rel = Convert.ToDateTime(rel.Trim()).ToString("yyyyMMdd");
try
{
List<TabTemp3> Listed = new List<TabTemp3>();
var connection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
DataTable dt = new DataTable();
string sqlcmd = "SELECT l.DESCRIZIONE, CASE WHEN m.PezziTurnoStd=0 THEN 0 ELSE (8 / CONVERT(decimal, m.PezziTurnoStd)) * pr.CostoOraDir * m.PersonaleDirettoStd END Totale FROM ";
sqlcmd = sqlcmd + "AHE.dbo.Inds0DbParArt AS m INNER JOIN ";
//... ETC ...
using (var dataAdapter = new SqlDataAdapter(sqlcmd, connection))
{
dataAdapter.Fill(dt);
}
foreach (DataRow row in dt.Rows)
{
Listed.Add(new TabTemp3
{
DESCRIZIONE = row["DESCRIZIONE"].ToString(),
Totale = (decimal)(row["Totale"])
});
}
var temp = Listed.AsEnumerable<TabTemp3>();
return Json(temp.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("" + e);
}
return null;
}

Related

MVC Ajax function call twice

I have a problem with an ajax function. I want to send param to method on controller and this ajax function call method twice.
ajax:
$(document).ready(function () {
$(document).on('click', '.exp', function (e) {
var st_date = $(this).parent().find('.start').val();
var ed_date = $(this).parent().find('.end').val();
$.ajax({
url: '/Reports/Report_CLeav/',
data: {
start_date:st_date,
end_date:ed_date
}
}).success(function (data) {
})
});
})
$(".exp").click(function() {
var st_date = $(this).parent().find('.start').val();
var ed_date = $(this).parent().find('.end').val();
$.ajax({
url: '/Reports/Report_CLeav/',
data: {
start_date:st_date,
end_date:ed_date
}
}).success(function (data) {
})
});
?
<th>
Start date: #Html.TextBox("start_date", null, new { #class = "dateClass start", id = "StartDate" })
End date: #Html.TextBox("end_date", null, new { #class = "dateClass end", id = "EndDate", #data_toggle = "popover", #data_content = "End date should be greater than Start date. ", #title = "Attention" })
#Html.ActionLink("Export Report", "Report_CLeav", "Reports", new { #class = "IndexButton exp", #style = "text-decoration: none;color:white" })
</th>
"Controller"
public class ReportsController : Controller
{
// GET: Export
public ActionResult Index()
{
return View();
}
public void Report_CLeav(DateTime ?start_date, DateTime ? end_date)
{
string path = HttpContext.Server.MapPath("~/App_Data/reports/Report_LeavingCompanyHCT.xlsx");
Models.Report.Report_CompLeav reportcompleav = new Models.Report.Report_CompLeav();
var fileinfo = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(fileinfo))
{
var currentWorksheet = package.Workbook.Worksheets["HC"];
using (var excelToExport = new ExcelPackage())
{
excelToExport.Workbook.Worksheets.Add(currentWorksheet.Name, currentWorksheet);
var workBook = excelToExport.Workbook.Worksheets["HC"];
try
{
workBook = reportcompleav.exportAllEmployeeDataRRecords(workBook,start_date,end_date);
}
catch (Exception e)
{
ViewBag.IsError = true;
}
excelToExport.Save();
Stream stream = excelToExport.Stream;
var memoryStream = stream as MemoryStream;
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats";
Response.AddHeader("Content-Disposition",
"attachment; filename=" + fileinfo.Name);
Response.BinaryWrite(memoryStream.ToArray());
}
}
}
}
}

Selecting Enum items on AJAX call

I am working on action result which returns JSON data to view and then loads on textFields by AJAX call
Action:
public ActionResult loadInf(string custm)
{
int smclientbranchid = Convert.ToInt32(Session["smclientbranchid"]);
var query = (from parent in db.Customer
join child in db.CustomerAddress on parent.CustomerId equals child.CustomerId
where parent.SMClientBranchId == smclientbranchid && parent.NIC == custm
select new SalesVM
{
Indicator = parent.Indicator,
//code removed
}).ToList();
return Json(query);
}
In View:
#Html.DropDownListFor(model => model.Indicator,
new SelectList(Enum.GetValues(typeof(ColorTypes))),
"<Select>",
new { #class = "form-control", id ="Indicator" })
<script type="text/javascript">
$(document).ready(function () {
$("#btnSearchCus").click(function () {
var custm = $('#custm').val();
$.ajax({
cashe: 'false',
type: "POST",
data: { "custm": custm },
url: '#Url.Action("LoadCustomerInfo", "Sales")',
dataType: 'json', // add this line
"success": function (data) {
if (data != null) {
var vdata = data;
$("#Indicator").val(vdata[0].Indicator);
//code removed
}
}
});
});
});
</script>
I am getting data right and also loading right except the "Indicator" field, which is of type enum.
How can I select an enum list item from the data I get.
For example:
0,1,2,3 index order
You need to be setting the Value attributes against all of the option values for the select list.
Use the following for your dropdown box to select by the text representation of the value:
#Html.DropDownListFor(model => model.Indicator, Enum.GetValues(typeof(ColorTypes)).Cast<ColorTypes>().Select(x => new SelectListItem { Text = x.ToString(), Value = x.ToString() }), new { #class = "form-control", id = "Indicator" })
Or use the following for it to select by the integer value:
#Html.DropDownListFor(model => model.Indicator, Enum.GetValues(typeof(ColorTypes)).Cast<ColorTypes>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }), new { #class = "form-control", id = "Indicator" })
This will allow your .Val() jQuery code to select the correct one.
If you retrieving string variable nm (0,1,2,3...) - would be better to change the type to int and try cast your integer variable to Enum type that you have.
public ActionResult loadInf(int nm)
{
ColorTypes enumValue = (ColorTypes) nm;
.......
You can take a look about details to this article: http://www.jarloo.com/convert-an-int-or-string-to-an-enum/

Kendo Grid not Paging data

I use Kendo Grid for my ASP.NET MVC app which uses ajax binding for the read.
It binds the data to the first page but does not show the number pages for the grid.
it shows (|< < 0 > >|).
Index.cshtml
#(Html.Kendo().Grid<Club.Areas.Admin.Models.Users>()
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("List1", "Home"))
.PageSize(5)
)
.Columns(columns =>
{
columns.Bound(p => p.Id).Filterable(false).Width(100);
columns.Bound(p => p.NickName).Width(100);
columns.Bound(p => p.UserVisitLastDate).Format("{0:MM/dd/yyyy}").Width(140);
columns.Bound(p => p.Mobile).Width(100);
})
.Pageable()
.Sortable()
.HtmlAttributes(new { style = "width:500px;height:430px;" })
)
HomeController
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult List1([DataSourceRequest]DataSourceRequest request)
{
List<Users> U = new List<Users>();
for (int i = 0; i < 100; i++)
{
U.Add(new Users
{
NickName = "Mehdi",
Company = "Taral",
Email = "M.Farokhtabar#Gmail.com",
Family = "FT",
HomeAddress = "Isfahan",
HomePhone = "03112332940",
IsActive = true,
Mobile = "09131025834",
Name = "Mehdi",
UserCreateDate = DateTime.Now,
UserVisitLastDate = DateTime.Now,
WebSite = "",
WorkAddress = "Mehdi",
PostalCode = "1234567890",
Id = i,
WorkPhone = "03117726250"
});
}
DataSourceResult result = U.ToDataSourceResult(request);
return Json(result,JsonRequestBehavior.AllowGet);
}
}
You will have to set serverPaging: true of the DataSource and make sure that the response from server has total field with the amount of the items.
My answer is not completely related to MVC approach, I have used this with WebAPI controller. The datasource should look something like this:
var sampleDataSource = new kendo.data.DataSource({
transport: {
read: {
url: svcSampleUrl,
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json"
},
parameterMap: function (options) {
model.Take = options.take;
model.Skip = options.skip;
model.Sort = options.sort;
model.Filter = options.filter;
return kendo.stringify(model);
}
},
schema: {
data: "sampleDTOList",
total: "totalItems",
model: {
fields: {
ID: { type: "number" },
Label: { type: "string" },
Description: { type: "string" }
}
}
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
The total attribute in the schema is where it gets the total number of records and calculates the number of pages to show. In your case you are receiving the data of the first page, and the grid does not know how much data there is in order to calculate the total number of pages there needs to be.

how to use cascading dropdownlist in mvc

am using asp.net mvc3, i have 2 tables in that i want to get data from dropdown based on this another dropdown has to perform.for example if i select country it has to show states belonging to that country,am using the following code in the controller.
ViewBag.country= new SelectList(db.country, "ID", "Name", "--Select--");
ViewBag.state= new SelectList("", "stateID", "Name");
#Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewBag.country, "-Select-")
#Html.DropDownListFor(model => model.state, (IEnumerable<SelectListItem>)ViewBag.state, "-Select-")
but by using this am able to get only the countries.
There is a good jQuery plugin that can help with this...
You don't want to refresh the whole page everytime someone changes the country drop down - an ajax call to simply update the state drop down is far more user-friendly.
Jquery Ajax is the best Option for these kind of questions.
Script Code Is Given below
<script type="text/javascript">
$(function() {
$("##Html.FieldIdFor(model => model.Country)").change(function() {
var selectedItem = $(this).val();
var ddlStates = $("##Html.FieldIdFor(model => model.state)");
$.ajax({
cache:false,
type: "GET",
url: "#(Url.Action("GetStatesByCountryId", "Country"))",
data: "countryId=" ,
success: function (data) {
ddlStates.html('');
$.each(data, function(id, option) {
ddlStates.append($('<option></option>').val(option.id).html(option.name));//Append all states to state dropdown through returned result
});
statesProgress.hide();
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to retrieve states.');
statesProgress.hide();
}
});
});
});
</script>
Controller:
public ActionResult GetStatesByCountryId(string countryId)
{
// This action method gets called via an ajax request
if (String.IsNullOrEmpty(countryId))
throw new ArgumentNullException("countryId");
var country = GetCountryById(Convert.ToInt32(countryId));
var states = country != null ? GetStatesByConutryId(country.Id).ToList() : new List<StateProvince>();//Get all states by countryid
var result = (from s in states
select new { id = s.Id, name = s.Name }).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Try this,
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
var Id = $("#Country").val();
$.ajax({
url: '#Url.Action("GetCustomerNameWithId", "Test")',
type: "Post",
data: { Country: Id },
success: function (listItems) {
var STSelectBox = jQuery('#state');
STSelectBox.empty();
if (listItems.length > 0) {
for (var i = 0; i < listItems.length; i++) {
if (i == 0) {
STSelectBox.append('<option value="' + i + '">--Select--</option>');
}
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
else {
for (var i = 0; i < listItems.length; i++) {
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
}
});
});
});
</script>
View
#Html.DropDownList("Country", (SelectList)ViewBag.country, "--Select--")
#Html.DropDownList("state", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")
Controller
public JsonResult GetCustomerNameWithId(string Country)
{
int _Country = 0;
int.TryParse(Country, out _Country);
var listItems = GetCustomerNameId(_Country).Select(s => new SelectListItem { Value = s.CountryID.ToString(), Text = s.CountryName }).ToList<SelectListItem>();
return Json(listItems, JsonRequestBehavior.AllowGet);
}

Internal Server Error on kendo grid update with ajax

i m trying to update grid with ajax but i couldn't success in passing and getting values between controler and view with ajax
When i run program its output is like that
[object Object]++error++Internal Server Error
So i need help
HomeController Function
[HttpGet]
public ActionResult RssCek(string value)
{
XDocument rssXml = new XDocument();
switch (value)
{
case "Ekonomi":
{
rssXml = XDocument.Load("http://sozcu.com.tr/rss.php");
break;
}
case "Siyaset":
{
rssXml = XDocument.Load("http://www.milliyet.com.tr/D/rss/rss/Rss_4.xml");
break;
}
case "Yaşam":
{
rssXml = XDocument.Load("http://www.milliyet.com.tr/D/rss/rss/Rss_5.xml");
break;
}
default:
{
rssXml = XDocument.Load("http://sozcu.com.tr/rss.php");
}
break;
}
var feedler = from feed in rssXml.Descendants("item")
select new Rss
{
Baslik = feed.Element("title").Value,
Link = "Oku",
Aciklama = feed.Element("description").Value
};
var valueToReturn = new JsonResult { Data = feedler };
return valueToReturn;
}
IndexView Grid Code
#Html.Kendo().Grid(Model)
.Name("Grid").Pageable()
.Columns(columns =>
{
columns.Bound(p => p.Baslik).Groupable(false);
columns.Bound(p => p.Aciklama).Encoded(false);
columns.Bound(p => p.Link).Encoded(false);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("RssCek", "Home"))
)
IndexView JavaScript Code
<script>
function select(e) {
var value = $(e.item).find("> .k-link").text();
$.ajax({
url: '#Url.Action("RssCek", "Home")',
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: { value: value},
success: function (feedler)
{
document.write(feedler);
},
error: function (request, status, error)
{document.write(request+"++"+ status+"++"+ error);}
});
}
</script>
I found problem is caused by missing JsonRequestBehavior.AllowGet
return Json(feedler, JsonRequestBehavior.AllowGet);
instead of ;
var valueToReturn = new JsonResult { Data = feedler };
return valueToReturn;

Resources