I have tried everything I know to do but I cannot seem to get this to work...
My goal is to show tickets submitted in the past two weeks. I have already done all the logic on the back side of my MVC project but I cannot seem to display it properly. I just get a blank line graph with the legend to the right. I have provided my Razor code and the JSON return data. Please help. Thanks.
#(Html.Kendo().Chart<NewTicketsTwoWeekGraph>()
.Name("TwoWeekTickets")
.DataSource(dataSource => dataSource
.Read(read => read.Action("NewTicketsData_Read", "Home"))
)
.Series(series =>
{
series.Line(d => d.TicketCount).Name("Ticket Count");
})
.CategoryAxis(axis => axis
.Categories(t => t.TicketDate).Date().BaseUnit(ChartAxisBaseUnit.Days)
.Labels(labels => labels.Rotation(-90))
.Crosshair(c => c.Visible(true))
)
.ValueAxis(axis => axis.Numeric()
.Labels(labels => labels.Format("{0:N0}"))
.MajorUnit(10)
)
)
JSON Return:
{"Data":[{"TicketCount":1,"TicketDate":"\/Date(1426651200000)\/","TicketDateString":"2015-03-18"},
{"TicketCount":2,"TicketDate":"\/Date(1426564800000)\/","TicketDateString":"2015-03-17"}],"Total":2,"AggregateResults":null,"Errors":null}
The problem was with the JSON data being sent back. It doesnt like be wrapped in the "Data" array.
So I changed up my ActionResult to fix this...
public ActionResult _NewTicketCtOverTwoWeeks_Read([DataSourceRequest]DataSourceRequest request, string username)
{
using (var ctx = new GuardianContext())
{
var startDate = DateTime.Now.AddDays(-14);
var graphData = from ticket in ctx.TICKETS
where ticket.CREATED > startDate
group ticket by DbFunctions.TruncateTime(ticket.CREATED)
into a
orderby a.Key
select new TicketCount() { TicketCt = a.Count(), TicketDate = (DateTime)a.Key, TicketDateString = a.Key.ToString().Substring(0, 10) };
return Json(graphData.ToList());
}
}
So now my JSON request returns the following...
[{"TicketCt":2,"TicketDate":"\/Date(1426564800000)\/","TicketDateString":"2015-03-17"},{"TicketCt":11,"TicketDate":"\/Date(1426651200000)\/","TicketDateString":"2015-03-18"},{"TicketCt":20,"TicketDate":"\/Date(1426737600000)\/","TicketDateString":"2015-03-19"}]
Related
I am new to laravel and I am facing following problem
My problem
Problem i m facing is that whenever I submit the form after filling firstname lastname and phone, then everything going well except one thing that in my MYSQL database data is save as firstname: NULL lastname:NULL And phone:NULL instead of saving the data which i had enter.
I have a angularjs form in which is there fields like firstname lastname and phone.on submit it goes to submitContact() in controller:
submit.js:
var addnew = angular.module('addnew',[]);
// create angular controller
addnew.controller('addContactController',
function($scope,$location,$window,$http) {
// function to submit the form after all validation has occurred
$scope.submitContact = function() {
$scope.addnew = {firstname:'', lastname:'',phone:''};
$scope.addnew.firstname=$scope.firstname;
$scope.addnew.lastname=$scope.lastname;
$scope.addnew.phone=$scope.phone;
$http.get("http://localhost:8000/index.php/user/addnew",{"firstname": $scope.firstname, "phone": $scope.phone, "lastname": $scope.lastname})
.then(function mysuccess(response) {
$scope.mycard = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
$window.alert(JSON.stringify(response));
console.log(response.data);
});
};
});
http://localhost:8000/index.php/user/addnew this links to my laravel through routes.
my route.php:
Route::get('/user/addnew', 'usercontroller#store');
my usercontroller.php
public function store(Request $request)
{
//contacts::create(Request::all());
$user = new contacts;// contacts is my table name and my database is defined in .env file
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->phone = Input::get('phone');
$user->save();
//I Used print_r to see that weather my submitted data is coming in $user or not:
print_r($user);
echo "saved";
}
my contact.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class contacts extends Model
{
protected $fillable =['firstname','lastname','phone'];
}
?>
Now, My problem
when i print_r $user then i got the error as my array is NOT catching my submitted data
print_r ($user) output in console window:
[fillable:protected] => Array
(
[0] => firstname
[1] => lastname
[2] => phone
)
[connection:protected] =>
[table:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[firstname] =>
[lastname] =>
[phone] =>
[updated_at] => 2016-10-07 03:46:34
[created_at] => 2016-10-07 03:46:34
[id] => 38
)
[original:protected] => Array
(
[firstname] =>
[lastname] =>
[phone] =>
[updated_at] => 2016-10-07 03:46:34
[created_at] => 2016-10-07 03:46:34
[id] => 38
)
I want to know where I m making mistake and how can I correct that mistake.
Thanking you in anticipation.
Try this:
$user = new Contact();
Instead of this:
$user = new contacts;
Also, change class name to class Contact extends Model and a filename to a Contact.php.
Alternatively, since you're using $fillable you can create new row:
Contact::create($request->all());
https://laravel.com/docs/5.3/eloquent#mass-assignment
I think you should use POST instead of GET.
$http.post("http://localhost:8000/index.php/user/addnew",{"firstname": $scope.firstname, "phone": $scope.phone, "lastname": $scope.lastname})
.then(function mysuccess(response) {
$scope.mycard = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
$window.alert(JSON.stringify(response));
console.log(response.data);
});
And
Route::post('/user/addnew', 'usercontroller#store');
And I noticed that you are posting to /index.php/user/addnew
And your route is '/user/addnew'
'/index.php/user/addnew' and '/user/addnew' are different.
try posting to localhost:8000/user/addnew instead
To explain:
/user/addnew always refer to host:port/user/addnew
While user/addnew will just concatenate it to your current url
for example if you're currently at: localhost:8000/users/1
Clicking a link to user/addnew will bring you to localhost:8000/users/1/user/addnew while a link to /user/addnew will bring you to localhost:8000/user/addnew
EDIT:
Is this redundant?
$scope.addnew.firstname=$scope.firstname;
$scope.addnew.lastname=$scope.lastname;
$scope.addnew.phone=$scope.phone;
What you were sending is this:
{"firstname": $scope.firstname, "phone": $scope.phone, "lastname": $scope.lastname}
I think you can send this instead:
$scope.addnew
and again, you should use POST, not GET.
did you already update your http request to post? did you update the url?
Actually, I achived this by using $request->input('firstname'); $request->input('firstname'); $request->input('firstname');, since, it was JSON thats why. Else, If I had been using Laravel blade file then I could have done it by above solutions.
I've a query, something like this
var ReportData = db.PY_History_TransactionTAB.AsEnumerable()
.Where(x => x.SystemCode == SysCode)
.GroupBy(x => new { x.EmployeeCode, x.EmployeeMaster.Emp_FullName});
For x.EmployeeCode selection of GroupBy member, it is easy to do :
ReportData.Select(x => new PY_History_TransactionTAB
{
EmployeeCode = x.Key.EmployeeCode,
}
But, what if I want to select the next GroupBy member i.e. x.EmployeeMaster.Emp_FullName, How do I do this? so that I get it right at my strongly typed view.
ReportData.Select(x => new
{
EmployeeCode = x.Key.EmployeeCode,
EmployeeName = x.Key.Emp_FullName,
}
I found the solution. So, if you have a navigation property, just place it in select() in this way :
ReportData.Select(x => new PY_History_TransactionTAB
{
EmployeeCode = x.Key.EmployeeCode,
EmployeeMaster = x.First().EmployeeMaster
}
Now you can have all properties of EmployeeMaster class as well.
I have a two kendo multiselect and i want my roles multiselect to sort of cascade from the other in a way that on the roles multiselect read i want to post a list of the values selected in my systems multiselect. This is what my roles multiselect looks like:
#(Html.Kendo().MultiSelect()
.Name("Roles")
.DataTextField("Name")
.DataValueField("Id")
.Placeholder("Select roles")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetRoles", "UserAdmin").Data("additionalItemsGetRoles");
})
.ServerFiltering(true);
})
)
<script>
function additionalItemsGetRoles() {
var multiselect = $("#Systems").data("kendoMultiSelect").dataItems();
var length = multiselect.length;
var systems = [];
for (var i = 0; i < length; i++) {
systems.push({
Name: multiselect[i].Name,
SystemId: multiselect[i].SystemId,
Description: multiselect[i].Description
});
}
var json = JSON.stringify(systems);
console.log(json);
return json;
}
</script>
and here is what my action method looks like:
public ActionResult GetRoles([DataSourceRequest] DataSourceRequest request, IList<SystemViewModel> systems)
{
And here is what my console.log(json) shows in the console.
And here is my viewmodel:
public string SystemId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
I tried to set the action method as [httpPost] but then it can't find the method at all.
Everytime it posts to the controller it get null. What am i doing wrong here?
OK, if I understand correctly, what you want to do is to filter one multiselect list, based on the selected items in another multiselect list. Yes?
I am actually doing something similar, and here is what I did:
First, setup the two MultiSelect "widgets"
Set the Change event on the first MultiSelect ("regionChange")
Set the .Data parameter of DataSource to a js function ("regionfilter")
#(Html.Kendo().MultiSelect()
.Name("region")
.DataTextField("Name")
.DataValueField("Id")
.AutoBind(false)
.Events(e => e.Change("regionChange"))
.DataSource(ds => ds
.Read(read => read.Action("GetRegionsForFilter", "Authorization")
)
)
#(Html.Kendo().MultiSelect()
.Name("branch")
.DataTextField("Name")
.DataValueField("Id")
.AutoBind(false)
.DataSource(ds => ds
.Read(read => read.Action("GetBranchesForFilter", "Authorization")
.Data("regionfilter"))
.ServerFiltering(true)
)
)
Define js functions (I have an additional function to get the MultiSelect values, because I am using this on a couple of other MultiSelect "widgets" no the page, AND I am actually doing reverse filtering for some (such as Branch/Region though I snipped out the filtering being done on region)
function regionChange() {
var value = this.value(),
grid = $("#grid").data("kendoGrid");
<-- snipped logic related to filtering grid -->
$('#branch').data('kendoMultiSelect').dataSource.read();
}
function regionfilter() {
var values = getMultiSelectValues("region");
return { regions: values.toString() };
}
function getMultiSelectValues(multiSelectControl) {
var multiSelect = $("#" + multiSelectControl).data("kendoMultiSelect");
var values = multiSelect.value($("#value").val());
return values;
}
Finally, in my controller I am just returning a JsonResult (get request) that accepts a string argument (comma separated list of strings)
public JsonResult GetBranchesForFilter(string regions)
{
var list = _repository.Branches().GetAll().Select(x => new { x.Id, x.Name, x.RegionId });
if (!String.IsNullOrWhiteSpace(regions))
list = list.Where(x => regions.Contains(x.RegionId.ToString()));
return Json(list.OrderBy(o => o.Name), JsonRequestBehavior.AllowGet);
}
I am working on Web API and using Anonymous type to make JSON as output. I am stuck in the following scenario:
If there is no record(VALUE) available then i don't want to show that KEY. Meaning, Key should only appear when and only when there is value.
Below is the JSON object i am creating -
"TU": [
{
"BLOCK": [
[
"00:00",
"00:59"
]
]
}
],
"WE": [],// empty
"TH": [],// empty
"FR": [],// empty
"SA": [] // empty
Here for Tuesday we do have records and hence its showing but later for WE,TH,FR,SA there are not records and hence i don't want to show them so my result will be MO/TU only.
I am using below code:
var result = new
{
CustomerID = custId,
DeviceID = dId,
Kind = kind,
WebList = filter.Select(filt => new
{
URL = filt.FilterName,
TimeBlockFlag = new ChicoHelper().GetFlag(browserlimit, filt.ID, filt.FilterOptionID, KindId),
DAILY = browserlimit.Where(xx => xx.FilterID == filt.ID && xx.OptionTypeID == daily).Select(xx => xx.BlockTimeLimit).SingleOrDefault(),
WEEKLY = browserlimit.Where(xx => xx.FilterID == filt.ID && xx.OptionTypeID == weekly).Select(xx => xx.BlockTimeLimit).SingleOrDefault(),
MONTHLY = browserlimit.Where(xx => xx.FilterID == filt.ID && xx.OptionTypeID == monthly).Select(xx => xx.BlockTimeLimit).SingleOrDefault(),
HASVALUES = browserlimit.Where(xx => xx.FilterID == filt.ID).Count() > 0 ? 1 : 0,
BLOCKTYPE = new ChicoHelper().GetBlockType(browserlimit,filt.ID,filt.FilterOptionID,KindId),
SU = blockedlimit.Where(x => x.OptionID == sunday && x.FilterID == filt.ID).GroupBy(x => new { x.BlockDay })
.Select(x => new
{
BLOCK = x.Select(y =>
new[] { y.BlockStartTime.MakeFormatedTime(), y.BlockEndTime.MakeFormatedTime() }
)
}),
MO = blockedlimit.Where(x => x.OptionID == monday && x.FilterID == filt.ID).GroupBy(x => new { x.BlockDay })
.Select(x => new
{
BLOCK = x.Select(y =>
new[] { y.BlockStartTime.MakeFormatedTime(), y.BlockEndTime.MakeFormatedTime() }
)
}),
TU = blockedlimit.Where(x => x.OptionID == tuesday && x.FilterID == filt.ID).GroupBy(x => new { x.BlockDay })
.Select(x => new
{
BLOCK = x.Select(y =>
new[] { y.BlockStartTime.MakeFormatedTime(), y.BlockEndTime.MakeFormatedTime() }
)
}),
// if i can put some condition like if there is not record for WE then don't show it.
WE = blockedlimit.Where(x => x.OptionID == wednesday && x.FilterID == filt.ID).GroupBy(x => new { x.BlockDay })
.Select(x => new
{
BLOCK = x.Select(y =>
new[] { y.BlockStartTime.MakeFormatedTime(), y.BlockEndTime.MakeFormatedTime() }
)
}),
The main reason for doing this is to reduce the JSON size which will be consumed by Mobile Devices.
Please help me with this.
The properties of an anonymous type are fixed at compile-time - you can't make them conditional. However, some other approaches you might want to think about:
You could investigate whether a property is still included in the JSON representation if its value is null. If it's not, you could add an extension method NullIfEmpty() which returns null if its input is empty.
You could try performing the JSON conversion from the anonymous type in code first, then delete any properties with an empty set of results, then just return that JSON object from the API. (I don't know Web API myself, but there must be a way of saying "Here's a JSON object - ask it for its string representation" rather than using an anonymous type.)
You could ditch the anonymous type entirely, and build up the JSON representation programmatically, setting just the properties you want.
In any approach, I would strongly advise you to extract a common method to come up with the property value based on a day of the week, so you can have:
...
SU = blockedLimit.GetDayBlocks(sunday),
MO = blockedLimit.GetDayBlocks(monday),
TU = blockedLimit.GetDayBlocks(tuesday),
...
There's no reason to have all that code repeated 7 times. In fact, I'd probably refactor that part before doing anything else - it'll make it easier to experiment.
I am using Kendo UI chart in one of my projects today noticed a weird behaviour in different browser, I have date on x-axis, and it is auto transforming dates in different browsers with different time zone.
Like in UTC+5 it is showing date range from 3/1/2014 to 3/31/2014 while in UTC-6 it is showing date range from 2/28/2014 to 3/30/2014.
Basically this is happening due to the difference between the timezones of the client and the server and the form these dates are trasnfered and re-created on both sides into Date (JS) /DateTime (.NET) objects.
Basically the whole situtation is explained in details here. The dataSource that the Chart is using is the same as the one that the Grid uses so there is not difference.
Here is some example code from a project I have which you can use. Check the requestEnd handler
#(Html.Kendo().Grid<KendoMVCWrappers.Models.Person>().Name("persons")
.DataSource(dataSource => dataSource
.Ajax()
.Events(ev => ev.RequestEnd("convert"))
.Model(model => model.Id(m => m.PersonID))
.Read(read => read.Action("GetPersons", "Home"))
.Update(up => up.Action("UpdatePerson", "Home"))
)
.Filterable()
.Columns(columns =>
{
columns.Bound(c => c.PersonID);
columns.Bound(c => c.Name);
columns.Bound(c => c.BirthDate);
columns.Command(cmd => cmd.Edit());
})
.Pageable()
.Sortable()
)
<script type="text/javascript">
function convert(e) {
if (e.response.Data && e.response.Data.length) {
var offsetMiliseconds = new Date().getTimezoneOffset() * 60000;
var persons = e.response.Data;
for (var i = 0; i < persons.length; i++) {
persons[i].BirthDate = persons[i].BirthDate.replace(/\d+/,
function (n) { return parseInt(n) + offsetMiliseconds }
);
}
}
}
</script>
And the setter code of the ViewModel. Using a setter eases the whole situation since you have to do it in multiple places (before creating an object when it is fetched from the database and when it is created from the ModelBinder).
public class Person
{
public int PersonID { get; set; }
public string Name { get; set; }
private DateTime birthDate;
public DateTime BirthDate
{
get { return this.birthDate; }
set
{
this.birthDate = new DateTime(value.Ticks, DateTimeKind.Utc);
}
}
}
Good luck!
Got null response error when tried to parse date as mentioned in this post in onRequestEnd.
http://www.telerik.com/support/code-library/using-utc-time-on-both-client-and-server-sides
I resolve this by parsing in datasource parse method instead of requestEnd.
parse :function(data)
{
return ConvertToUTC(data);
}
function ConvertToUTC(data)
{
// iterate over all the data elements replacing the Date with a version
// that Kendo can work with.
$.each(data, function(index, item){
if(index == "data")
{
for(i =0 ;i< item.length; i++)
{
// Days is my date property in item collection
item[i].Days = item[i].Days.replace(/\d+/,
function (n) {
var time = parseInt(n);
return parseInt(time) + new Date(time).getTimezoneOffset() * 60000;
}
);
}
}
});
return data;
}