im using this guide http://jqueryui.com/autocomplete/#custom-data and what little i know of C# and razor to try autocomplete 3 textboxes whenever one of them is picked.
so if i type in the partno and choose one from the drop down list, item name, desc and ID are populated. and the same if i type in any other field.
i have created a class and put it in a list with the items in
var varItems = new List<Item>();
varItems = db.Items.Select(tbl => new Item
{
ID = tbl.ID,
Name = tbl.Name,
PartNo = tbl.PartNo,
Description = tbl.Description
}).ToList();
then sent that in a viewbag
ViewBag.Items = var.items;
then in the view
$( "#Name" ).autocomplete({
minLength: 0,
source: #ViewBag.Items,
focus: function( event, ui ) {
$( "#Name" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#Name" ).val( ui.item.Name );
$( "#PartNo" ).val( ui.item.PartNo );
$( "#Description" ).html( ui.item.Description );
return false;
}
});
but it doesnt like the viewbag being there. im guessing i have to do some sort of loop to produce something like the below?
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
if so how do i loop my list to create the above?
Thanks guys
try this:
source: #Html.Raw(Json.Encode(#ViewBag.Items));
This would encode your Items to json and it should work.
Related
I am new to using react.js, using a C# API, and trying to use the semantic-UI dropdown that allows HTML in the content of the dropdown items.
I'm having trouble returning the "content" field below. It looks like a jsx:element type, not a string or number like the other types.
I can hardcode it, but I can't return it from the API.
Here is the example from the Semantic documentation which seems like an invalid JSON to me. For now, I've given up on this, but still curious how JSON like this is supposed to be returned from c# .net core API.
const options = [
{
key: 1,
text: 'Mobile',
value: 1,
content: (
<Header icon='mobile' content='Mobile' subheader='The smallest size' />
),
},
{
key: 2,
text: 'Tablet',
value: 2,
content: (
<Header
icon='tablet'
content='Tablet'
subheader='The size in the middle'
/>
),
},
{
key: 3,
text: 'Desktop',
value: 3,
content: (
<Header icon='desktop' content='Desktop' subheader='The largest size' />
),
},
]
This is my the code in the API that currently sends the dropdown items:
[HttpGet(Name = "GetCaseDropdown")]
public IEnumerable<CaseDropdownItem> Get()
{
var db = new CaseDBContext();
var records = (from x in db.Cases
select new CaseDropdownItem()
{
content = "<b>"+ x.StrCnCasenum + "</b>" + " " + x.StrCnName, // Does not render within parentheses which is required
text = x.StrCnName,
value = x.StrCnCasenum,
key = x.StrCnCasenum
}).ToArray();
return records;
}
And the react code that fetches the data:
fetch("casedropdown")
.then((response) => response.json())
.then((data) =>
setCaseOptions(
data.map((x) => {
return { key: x.key, text: x.text, value: x.value, content: x.content };
})
)
);
I am making a call to my MVC controller and return a list of objects to angular (javascript)
I want to bind it to a Kendo Treelist with arrows on the left such that when the user expands i can get the value of the parent , get the children associated with the parent and bind below the parent.
Here is what i have tried
HTML Code:
<div kendo-tree-list id="treeView" k-options="sourceOptions"></div>
Javascript:
This is defined in the beginning of the javascript file:
$("#treeView").kendoTreeList({
dataSource: $scope.userdetails,
toolbar: ["create"],
editable: "popup",
height: 540,
columns: [
{ field: "Id", expandable: true, title: "Id", width: 250 },
{ field: "FirstName", title: "FirstName", width: 250 },
{ field: "LastName", title: "LastName", width: 250 },
{ command: [{ name: "createchild", text: "Add child" }, "edit", "destroy"], width: 300 }
]
});
This bit of javascript is called only when a value in a dropdown is selected.
if ($scope.company!= undefined && $scope.company!= null && $scope.company.length > 0) {
myService.getAllUsers({
Name: $scope.company
}).then(function (result) {
if (result.data != null && result.data.userdetails) {
var treelist = $("#treeView").data().kendoTreeList;
var newDs = new kendo.data.TreeListDataSource({
data: result.data.userdetails,
schema: {
model: {
id: "Id",
fields: {
Id: { type: "string"},
FirstName: { type: "string" },
LastName: { type: "string" }
},
expanded: false
}
}
});
treelist.setDataSource(newDs);
}
});
}
};
So there is a dropdownlist that is populated with a number of companies. When the user selects a company from the list , it will call getAllUsers and retrieve all users in a company from MVC and return a javascript object, I want to bind that to the treeview.
When its bound , each parent should have a arrow on the left which will allow it to be expanded and only when they expand , i want to call another MVC actionresult that will retrieve the child data for that selected value. The child result will have checkboxes allowing the user to select and child fields on the parent.
If they select a different company from the main list , then the treeview will be cleared and repopulated
It doesnt seem to be binding at all, any ideas with this ?
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 "";
}
}
I am a beginner in using jQuery Float Chart. Now I try to bind the chat with server side values. I need to build an array structure like below.
data = [{
label: 'Test 1',
data: [
[1325376000000, 1200],
[1328054400000, 700],
[1330560000000, 1000],
[1333238400000, 600],
[1335830400000, 350]
]
},];
My Server Response
My question is how to push items in this array of array. I already try to build an array like this:
var data = new Array();
var chartOptions;
$.each(graphdata, function (key, value) {
data.push({
label: value.label,
data: $.each(value.data, function (key, value) {
Array(value.X, value.Y);
})
})
});
Edits
Graph shows in webpage
But it's not working.
The problems is that $.each return collection that iterates on - the collection you don't want to.
You can use underscore library that contains function map to project value into another:
var postData = [{label:"test1", "data": [ {X: "10", Y:"11"}, {X: "12", Y: "13"}] }];
var data = []
$.each(postData, function (key, value) {
data.push({
label: value.label,
data: _(value.data).map(function(innerVal) {
var arr = new Array();
arr.push(innerVal.X);
arr.push(innerVal.Y);
return arr;
})
})
});
Here is jsFiddle: click!
On the following grid grouping example. How can I display The first group as (0 Countries), if no data is returned for the first record.
Currently, if there are no records, the first group does not appear
What I need to do is, show the first group with (0) count and not just make it disappear. Is there way to still show up the group header, even if there is no data, like a default header or something? Any ideas? I need to do this for all the 4 headers
Update
Ext.require(['Ext.data.*', 'Ext.grid.*']);
Ext.onReady(function() {
Ext.define('Country', {
extend: 'Ext.data.Model',
fields: ['name']
});
var Country = Ext.create('Ext.data.Store', {
storeId: 'country',
model: 'Country',
groupField: 'countryName',
proxy: {
type: 'ajax',
scope: this,
url: 'myExtjsApp/ExtjsGetRecord',
reader: {
type: 'json',
root: 'data'
}
}
});
var groupingFeature = Ext.create('Ext.grid.feature.Grouping',{
groupHeaderTpl: '{name} ({rows.length} Item{[values.rows.length > 1 ? "s" : ""]})'
});
var grid = Ext.create('Ext.grid.Panel', {
renderTo: Ext.getBody(),
collapsible: true,
iconCls: 'icon-grid',
frame: true,
store: Country,
width: 600,
height: 400,
title: 'Country',
features: [groupingFeature],
columns: [{
text: 'Country',
flex: 1,
dataIndex: 'name'
}]
});
});
side topic:
for your header template you can also use plural format function instead of just adding 's': (which ironically this does if you don't pass singular and plural arguments)... just a thought.
http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.util.Format-method-plural