Entity sql datetime literal - asp.net-mvc

I am stuck in the ObjectQuery class it always gives me the error as
System.Data.Entity: The argument types 'Edm.DateTime' and 'Edm.String' are incompatible for this operation., near WHERE predicate
Please suggest me the solution, i followed the above approach, but it did not work.
my code is as follows:
C# code:
var _dbModel = new VISAIntBPAEntities();
var serializer = new JavaScriptSerializer();
Filters f = (!_search || string.IsNullOrEmpty(filters)) ? null : serializer.Deserialize<Filters>(filters);
//if (f != null)
//{
// if (f.rules[0].field == "CreatedDate")
// {
// Convert.ToDateTime(f.rules[0].data).ToString();
// }
//}
ObjectQuery<Jobs> filteredQuery = (f == null ? _dbModel.Jobs : f.FilterObjectSet(_dbModel.Jobs));
//if (f != null)
//{
// if (f.rules[0].field == "CreatedDate")
// {
// filteredQuery.Parameters.Add(new ObjectParameter("CreatedDate", Convert.ToDateTime(f.rules[0].data)));
// }
//}
if (f != null)
{
DateTime dateTimeValue = Convert.ToDateTime(f.rules[0].data);
filteredQuery = filteredQuery.Where(string.Format("(it.CreatedDate = DATETIME'{0:yyyy-mm-dd hh:mm}')", dateTimeValue));
}
filteredQuery.MergeOption = MergeOption.NoTracking; // we don't want to update the data
var totalRecords = filteredQuery.Count();
Cleint side code:
this code is in built using jqgrid, which has a column called CreatedDate, which fills in the dropdown, i have a sql query which fetches me the distinct date part from the database.
I am doing filtering based on the string date selection in the dropdown.
{
name: 'CreatedDate', index: 'CreatedDate', width: 140, stype: 'select', async: false, sorttype: 'date',
edittype: 'select', editoptions: { value: getCreatedJobDate() }, editable: true, formatoptions: { newformat: 'm/d/Y' },
//editrules: { required: true },
searchoptions: {
value: getCreatedJobDate,
sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'de']
}
}
Please help me as i am stuck with this approach, i need to do this way only.
Thanks in advance.

The commented code show that you already experimented with ObjectParameter. You can do
filteredQuery = filteredQuery.Where("it.CreatedDate = #createDate");
var par = new ObjectParameter("createDate", dateTimeValue);
filteredQuery.Parameters.Add(par);
And the SQL code will show something like
DECLARE #createDate DateTime = '2002-11-06 00:00:00.000'
followed by the query itself.

Related

How to perform server side filtering on Kendo UI Grid

I am trying to implement server side filtering for a Kendo UI grid (client only). I am not sure how to pass the filter operator and value entered on the filter box. I was able to implement server paging and want the filtering to work alongside the server paging, i.e. show page 2 of 5 items of filtered rows. I saw some example of binding the request to "DataSourceRequest" object but we do not have licence for the server side Kendo UI and have to achieve it using the client side changes only.
Here is my jQuery code:
var page = 1;
var pageSize = 5;
var title = "test";
var selectWork = function (e) {
alert("selected");
};
$("#selectWorkGrid").empty();
$("#selectWorkGrid").kendoGrid({
dataSource:
{
transport: {
read: {
url: "http://example.com/" + "work/SearchWorkJ?worktitle=" + title,
dataType: "json",
contentType: "application/json",
data: {
page: page,
pageSize: pageSize
}
},
serverFiltering: true,
parameterMap: function (data, type) {
if (type == "read") {
return {
page: data.page,
pageSize: data.pageSize
}
}
}
},
schema: {
model: {
id: "workId",
fields: {
workId: { type: "number" },
workTitle: { type: "string" },
writers: { type: "string" },
durationInMmSs: { type: "string" }
}
},
data: "data",
total: "total"
},
pageSize: pageSize,
serverPaging: true,
serverFiltering: true
},
sortable: true,
resizable: true,
columnMenu: false,
filterable: {
mode: "row",
extra: false,
operators: {
string: {
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to"
}
}
},
noRecords: {
template: "No results available."
},
pageable: {
numeric: false,
refresh: true,
buttonCount: 15
},
scrollable: false,
columns: [
{
field: "workTitle",
title: "Title",
template: "#=workTitle#"
},
{
field: "writers",
title: "Writers",
filterable: false,
template: "${writers == null ? '':writers}",
width: 300
},
{
field: "durationInMmSs",
title: "Duration",
filterable: false,
headerAttributes: { style: "text-align:right;" },
attributes: { style: "text-align:right;" },
width: 80
},
{ command: { text: "Select", click: selectWork }, title: "", width: 60 }
]
});
Controller action returning json:
public ContentResult SearchWorkJ(string workTitle, int page = 0, int pageSize = 0)
{
var worksJson = "";
var works = WorkService.SearchWork(workTitle, page, pageSize);
if (works != null)
{
// Set total to upto current record + 1 so that next button works in kendo
int totalCount = page * pageSize + 1;
var sortedWorks = new List<WorkViewModel>();
sortedWorks.AddRange(works.Select(w => new WorkViewModel
{
WorkId = w.WorkId,
WorkTitle = w.WorkTitle,
Writers = w.Writers,
DurationInMmSs = w.Duration
}).OrderBy(w => w.WorkTitle));
worksJson = JsonConvert.SerializeObject(new { total = totalCount, data = sortedWorks });
}
return new ContentResult { Content = worksJson, ContentType = "application/json" };
}
If you look at this
https://dojo.telerik.com/EhUNUwOr
<div id="my-grid"></div>
<script>
$('#my-grid').kendoGrid({
dataSource: {
serverFiltering: true,
serverSorting: true,
serverPaging: true,
pageSize: 5,
transport: {
read: function(options) {
$.ajax({
url: '/yourapi',
contentType: 'application/json',
dataType: 'json',
type: 'POST',
data: JSON.stringify(options.data),
success: function(result) {
options.success(result);
}
})
}
},
schema: {
id: 'Id',
data: 'Data',
total: 'Total',
errors: 'Errors',
fields: [
{ field: 'Id', type: 'number' },
{ field: 'FirstName', type: 'string' },
{ field: 'LastName', type: 'string' }
]
},
filter: {
filters: [{ field: 'FirstName', operator: 'eq', value: 'David' }]
}
},
});
</script>
This will send
{"take":5,"skip":0,"page":1,"pageSize":5,"filter":{"filters":[{"field":"FirstName","operator":"eq","value":"David"}]}}
to your server / api
now if you have a model that shares this structure you can respond in the following format
{
"Data" : <your array of models>,
"Total" : the number of models that fits your filter regardless of the filter, this helps kendo grid knowing how many pages there is for the pager.,
"Errors" : is mostely used for create and update so just return null
}
From here its a bonus to the answer above.
I noticed you are using CSharp so you have two options to apply create dynamic queries from Queryable.
use a library I open sourced
https://github.com/PoweredSoft/DynamicLinq
which is available on Nuget https://www.nuget.org/packages/PoweredSoft.DynamicLinq/
There is an example you can look at on git hub.
You'll have to adapt the code around but it should get you started.
https://github.com/PoweredSoft/DynamicLinq#how-it-can-be-used-in-a-web-api
[HttpGet][Route("FindClients")]
public IHttpActionResult FindClients(string filterField = null, string filterValue = null,
string sortProperty = "Id", int? page = null, int pageSize = 50)
{
var ctx = new MyDbContext();
var query = ctx.Clients.AsQueryable();
if (!string.IsNullOrEmpty(filterField) && !string.IsNullOrEmpty(filterValue))
query = query.Query(t => t.Contains(filterField, filterValue)).OrderBy(sortProperty);
// count.
var clientCount = query.Count();
int? pages = null;
if (page.HasValue && pageSize > 0)
{
if (clientCount == 0)
pages = 0;
else
pages = clientCount / pageSize + (clientCount % pageSize != 0 ? 1 : 0);
}
if (page.HasValue)
query = query.Skip((page.Value-1) * pageSize).Take(pageSize);
var clients = query.ToList();
return Ok(new
{
total = clientCount,
pages = pages,
data = clients
});
}
An alternative is using
https://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library

ChartJs Uncaught ReferenceError for labels value from ViewBag

I'm struggling with passing the csv strings via ViewBag in the correct format.
I know the result should be like ["Blue","Brown","Green"] but my script is generated as [Blue,Brown,Green] instead.
And then I get the Uncaught ReferenceError : Blue is not defined.
How can I format it in my controller to pass in the correct way?
This is my code in the controller
public ActionResult Index()
{
List<string> teamsList = new List<string>();
List<string> salesCount = new List<string>();
foreach (var team in Db.Teams)
{
teamsList.Add(team.Name);
int count = Db.LeadCampaigns.Count(i => Db.Agents.FirstOrDefault(a => a.AgentId == i.AgentId).TeamId == team.TeamId && i.LeadStatusId == Db.LeadStatuses.FirstOrDefault(s => s.Name == "SALE").LeadStatusId);
salesCount.Add(count.ToString());
}
ViewBag.SaleCount_List = string.Join(",", salesCount);
ViewBag.TeamName_List = string.Join(",", teamsList);
return View();
}
And here is my script in the view.
<script>
var barChartData =
{
labels: [#Html.Raw(ViewBag.TeamName_List)],
datasets: [{
label: 'TeamWise Sales Count',
backgroundColor: [
"#f990a7",
"#aad2ed",
"#9966FF",
"#99e5e5",
"#f7bd83",
],
borderWidth: 2,
data: [#ViewBag.SaleCount_List]
}]
};
window.onload = function () {
var ctx1 = document.getElementById("barcanvas").getContext("2d");
window.myBar = new Chart(ctx1,
{
type: 'bar',
data: barChartData,
options:
{
title:
{
display: true,
text: "TeamWise Sales Count"
},
responsive: true,
maintainAspectRatio: true
}
});
}
Your plugin expects an array of values, but your passing it a string by using String.Join().
Pass the array using
ViewBag.SaleCount_List = salesCount;
ViewBag.TeamName_List = teamsList;
(or better pass a view model with 2 IEnumerable<string> properties) and then convert it to a jacascript array
var saleCounts = #Html.Raw(Json.Encode(ViewBag.SaleCount_List))
var teamNames = #Html.Raw(Json.Encode(ViewBag.TeamName_List))
var barChartData =
{
labels: teamNames,
datasets: [{
....
],
borderWidth: 2,
data: saleCounts
}]
};
Using your current syntax:
const string quote = "\"";
foreach (var team in Db.Teams)
{
teamsList.Add(quote + team.Name + quote);
int count = Db.LeadCampaigns.Count(i => Db.Agents.FirstOrDefault(a => a.AgentId == i.AgentId).TeamId == team.TeamId && i.LeadStatusId == Db.LeadStatuses.FirstOrDefault(s => s.Name == "SALE").LeadStatusId);
salesCount.Add(count.ToString());
}

Override Ascending Descending functions - ui-grid

I'm using grid view for my reporting view. I need to override functions on Sort Ascending and Sort Descending event.
Here is my code for gridOptions.
var dynamicColumnDefs = _.map(_.keys(res[0]), function (key) {
return {name: key, field: key, width: '10%', enableHiding: false};
});
console.log('columnDefs', dynamicColumnDefs);
scope.gridOptions = {
data: res,
enableColumnResize: true,
enableGridMenu: true,
exporterMenuPdf: false,
columnDefs: dynamicColumnDefs,
enableHorizontalScrollbar: 2,
enableVerticalScrollbar: 2,
onRegisterApi: function (gridApi) {
// I hope I need to overide my function here
}
};
I need to trigger the event once I click Ascending and Descending only. How can I do it.
Thank you
I can do that;
scope.gridOptions = {
data: res,
enableColumnResize: true,
enableGridMenu: true,
exporterMenuPdf: false,
columnDefs: dynamicColumnDefs,
enableHorizontalScrollbar: 2,
enableVerticalScrollbar: 2,
onRegisterApi: function (gridApi) {
scope.gridApi = gridApi;
scope.gridApi.core.on.sortChanged(scope, scope.sortChange);
sortChanged(scope.gridApi.grid, [scope.gridOptions.columnDefs[1]]);
}
};
sortChanged = function (grid, sortColumns) {
// Do Whatever I want
}

In MVC 3, how do I refresh kendo grid in a partial view after I select a row in another partial view Kendo Grid?

I have a view with 3 partial views. The first partial view has a Kendo grid and when you select a row in the grid it populates and displays the 2nd partial view which has another kendo grid. It also populates and displays the 3rd partial view with another grid.
If I select a row in the 2nd kendo grid, i want it to insert data into the database table that the 3rd grid is using and I want it to refresh that 3rd grid with the new data.
I also have a custom button(retire) in the 3rd grid on each row that will also need to update that same grid by removing the item that was retired.
Can anyone help me set this up? Should I be using 3 partial views?
I guess you are using partial views to load each grid and it's data, that will work but you will have to refresh the entire page when a row is selected on the second grid in order to fill the third grid.
However Kendo Grid to a remote data source works well for this, you can then ignore loading the data into the grids within your partial views and use a bit of jQuery to ask the third grid to update on change event.
I find it much faster to fill grids with data via Ajax then when the page loads - but I have lots of data!
I have a grid updating for a person search which updates every time the search textbox changes
Grid defined as:-
$("#PersonSearch").kendoGrid({
columns: [
{ title: "Organisation", field: "cn", encoded: true },
{ title: "First name", field: "fn", encoded: true },
{ title: "Last name", field: "ln", encoded: true },
{ title: "Type", field: "pt", encoded: true },
{ title: "Date of birth", field: "db", encoded: true, format: "{0:dd/MM/yy}" },
{ title: "NHS number", field: "nn", encoded: true }
],
//sortable: { mode: "multiple" },
change: function () {
var selected = this.select()
data = this.dataSource.getByUid(selected.data("uid"));
if (data.url != "") {
.... do anything on a row being selected
}
else {
this.clearSelection();
}
},
filterable: false,
scrollable: { virtual: true },
sortable: true,
selectable: true,
groupable: false,
height: 480,
dataSource: {
transport: { read: { url: "../Person/PeopleRead/", type: "POST" } },
pageSize: 100,
serverPaging: true,
serverSorting: true,
sort: [
{ field: "cn", dir: "asc" },
{ field: "ln", dir: "asc" },
{ field: "fn", dir: "asc" },
],
serverFiltering: true,
serverGrouping: true,
serverAggregates: true,
type: "aspnetmvc-ajax",
filter: [],
schema: {
data: "Data", total: "Total", errors: "Errors",
model: {
id: "cID",
fields: {
db: { type: "date", defaultValue: null }
}
}
}
}
});
I trigger the Grid to fill with more data when the search box is changed :-
$('#GenericSearchString').keyup(function () {
// get a reference to the grid widget
var grid = $("#PersonSearch").data("kendoGrid");
// refreshes the grid
grid.refresh();
grid.dataSource.transport.options.read.url = "../Person/PeopleRead/" + $(this).val();
grid.dataSource.fetch();
});
On the server side in the Person controller I have a method PeopleRead :-
[HttpPost]
public ActionResult PeopleRead(String id, [DataSourceRequest]DataSourceRequest request)
{
WebCacheController Cache = ViewBag.Cache;
if (id == null) id = "";
string urlBase = Url.Content("~/");
var PeopleList = from c in db.Connections
where c.Person.Firstname.Contains(id) || c.Person.LastName.Contains(id)
select new
{
oID = c.Organisation.OrganisationID,
connID = c.ConnectionID,
cn = c.Organisation.Name,
fn = c.Person.Firstname,
pt =
(
c.Type == ModelEnums.ConnectionTypes.Customer ? "Customer" :
c.Type == ModelEnums.ConnectionTypes.Owner ? "Owner" :
c.Type == ModelEnums.ConnectionTypes.Service_User ? "Service user" :
c.Type == ModelEnums.ConnectionTypes.Worker ? "Worker" :
c.Type == ModelEnums.ConnectionTypes.Profile ? "Profile" : "Unknown"
),
url =
(
c.Type == ModelEnums.ConnectionTypes.Customer ? "" :
c.Type == ModelEnums.ConnectionTypes.Owner ? "" :
c.Type == ModelEnums.ConnectionTypes.Service_User ? urlBase + "ServiceUser/Details/" :
c.Type == ModelEnums.ConnectionTypes.Worker ? urlBase + "Worker/Details/" :
c.Type == ModelEnums.ConnectionTypes.Profile ? "" : ""
),
ln = c.Person.LastName,
nn = c.Person.NHSNumber,
db = c.Person.DateOfBirth
};
DataSourceResult result = PeopleList.ToDataSourceResult(request);
return Json(result);
}
Sorry the example is a bit off topic, but I though better to have working code as an example.
In your case the change: of the second grid would change the grid3.dataSource.transport.options.read.url and then do a grid3.dataSource.fetch();
I have to include the reference kendo.mvc along with many more on the mvc project as well as a link to kendo.aspnetmvc.min.js in the cshtml.

jqGrid boolean or enumeration dropdown filtering for columns

I'm using jqGrid to display tabular data on my first ASP.NET MVC 3 and find it really useful, particularly filtering down data. For string-type I use the column-filtering with "contains" and that works wonderfully for culling out the strings. For the date data I use the date picker. Great.
Now I've got a few columns (e.g., "Contains nuts") which are essentially boolean values. I want to provide a way to filter these. Right now they are displayed as "true" and "false" and use the same string-based filtering that my string-type columns use. That's a bit clunky. I think what I'd like to do instead is have a way to choose one of three values (true/false/both) via a dropdown mechanism.
My current colModel has an entry like so for my 'boolean' field:
{ name: 'ContainsNuts',
index: 'ContainsNuts',
align: 'left',
searchoptions: { sopt: ['eq, 'ne']}
}
which only works when the user types in 'false' or 'true' - again, clunky.
For a few other columns, I wanted to use dropdowns for enumerations, e.g., I have a 'Cones' column, since there are quite a few rows and I page the results - using the auto complete text filtering is a bit hit-or-miss for the user to find all the possible values. Hope that makes sense.
So what I've tried is this - I created a controller action that looks like so:
public JsonResult AvailableCones()
{
var context = new IceCreamEntities();
var query = context.Cones.AsQueryable().Distinct();
List<string> all = query.Select(m => m.Name).ToList();
return Json(all, JsonRequestBehavior.AllowGet);
}
And I did something like this [perhaps convoluted approach] to create a dropdown selection in the filtering dialog for Cones in my document ready:
...
createSearchSelection = function (someValues) {
var outputValues = "";
if (someValues && someValues.length) {
for (var i = 0, j = someValues.length; i < j; ++i) {
var entry = someValues[i];
if (outputValues.length > 0) {
outputValues += ";";
}
outputValues += entry + ":" + entry;
}
}
return outputValues;
}
setTheSearchSelections = function (colName, url){
$('#icecreamgrid').jqGrid('setColProp', colName,
{
stype: 'select',
searchoptions: {
value: createSearchSelection(url),
sopt: ['eq']
}
});
}
gotData = function(data) {
setTheSearchSelections('ConeType', data);
}
var url = "/IceCream/AvailableConeTypes";
$.get(url, null, gotData);
The result is that I get a drop-down for the ConeType column in the search dialog and the correct rows shows up in the column. Great. That's pretty cool that it works.
What I don't know how to do, however, is to get a dropdown to show up in my column header filter just like the one that now shows up in the filter dialog. How can I augment what I have to make this happen? Secondly, how can I make what I've got work for boolean values?
First part of your question is the displaying and filtering of the boolean values. I use checkboxes to display such values. In difference on your case I have typically many such columns. To reduce the size of the JSON data I use "1" and "0" instead of "true" and "false". Next I use the following column settings
formatter: 'checkbox', align: 'center', width: 20,
edittype: 'checkbox', editoptions: { value: "1:0" },
stype: "select", searchoptions: { sopt: ['eq', 'ne'], value: "1:Yes;0:No"
So for the searching the user have to choose "Yes" or "No" in the select box. Because I have many of such columns I defined templateCeckbox object in one JavaScript file which I include on every page of the project:
my.templateCeckbox = {
formatter: 'checkbox', align: 'center', width: 20,
edittype: 'checkbox', editoptions: { value: "1:0" },
stype: "select", searchoptions: { sopt: ['eq', 'ne'], value: "1:Ja;0:Nein" }
};
Then the typical column definition is
{
name: 'IsInBasis', index: 'InBasis', template: my.templateCeckbox,
cellattr: function () { return ' title="TS-Basis"'; }
},
(see the answer for details about the column templates). I find also practical if the tooltip shown if one hover the checkbox will be the text close to the column header. So I use cellattr attribute. In case of having many columns with the checkboxes it improves the usability a little.
To be able to display many columns with chechboxes I use personally vertical column headers. I recommend you to read the old answer which could be additionally interesting because it describes how to implement quick filtering of the data with respect of external checkbox panel.
Now about the building of the selects for the 'Cones' column. If you has AvailableCones action which provide the list of possible options like array (list) of strings you should use dataUrl:'/IceCream/AvailableConeTypes' instead of value: createSearchSelection(url) as the searchoptions. You well add only the buildSelect function which I described in "UPDATED" part of the answer.
{
name: 'ConeType', width: 117, index: 'ConeType', editable: true, align: 'center',
edittype: 'select', stype: 'select',
editoptions: {
dataUrl: urlBase + '/AvailableConeTypes',
buildSelect: my.buildSelect
},
searchoptions: {
dataUrl: urlBase + '/AvailableConeTypes',
buildSelect: my.buildSelect
}
}
where
my.buildSelect = function(data) {
var response = jQuery.parseJSON(data.responseText),
s = '<select>', i, l, ri;
if (response && response.length) {
for (i=0, l=response.length; i<l; i += 1) {
ri = response[i];
s += '<option value="' + ri + '">' + ri + '</option>';
}
}
return s + '</select>';
};
This line of code shows a True,False dropdownlist for a column that has true, false values:
{
name: 'SReqdFlag', index: 'SReqdFlag', editable: true, edittype: 'select', editoptions: { value: '"":Select;true:True;false:False' }
}
Hope that helps!

Resources