How to update multiple fields using JsonResult and Ajax DropDown - javascript

I have JsonResult list of Articles and it looked like this:
[
{
"tbl_dobavuvaci": null,
"tbl_fakDet": null,
"tbl_fakMas": null,
"tbl_kompanii": null,
"tbl_useri": null,
"artID": 1,
"artKompID": 1,
"artUserID": 1,
"artCode": 25456658845646540,
"artIme": "Artikal 1 Ime",
"artCenaNab": 10,
"artCenaProd": 15,
"artDDV": 18,
"artDobavuvac": 1
},
{
"tbl_dobavuvaci": null,
"tbl_fakDet": null,
"tbl_fakMas": null,
"tbl_kompanii": null,
"tbl_useri": null,
"artID": 2,
"artKompID": 1,
"artUserID": 1,
"artCode": 8606010872303,
"artIme": "TestName",
"artCenaNab": 25,
"artCenaProd": 30,
"artDDV": 18,
"artDobavuvac": 1
}
]
Now in HTML View i have javascript:
$(document).ready(function () {
$.getJSON("/fakturi/getArticles", function (data) {
$.each(data, function (i, data) {
$('<option>',
{
value: data.artID,
text: data.artCode
}).html;
});
})
$(function () {
$("[name='bar']").on("change", function () {
$("#artikal").val($(this).val());
});
});
});
Now When i change artCod named dropdown with artCode values from Json, corectly updated second field with artIme name.
HTML CODE:
#Html.DropDownList("bar", null, string.Empty, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.tbl_artikli, "", new { #class = "text-danger",})
#Html.DropDownList("artikal", null, string.Empty, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.tbl_artikli, "", new { #class = "text-danger", })
#Html.TextBox("artCenaProd", "", new { #class = "form-control", #id = "artCenaProd", style = "width:60pt" })
My Question is how to update third field named artCenaProd when I will change dropdown?

You need to store the json array you receive from your ajax call to a local variable in your script. When the dropdown change event is fired, read the selected option and get the option value (artID). Now filter the local array for items with this id and get the subset (If the artID's are unique, you will get a sub array with one it.
$(document).ready(function () {
var localData = [];
var $bar = $("[name='bar']");
$.getJSON("#Url.Action("/fakturi/getArticles")",
function(data) {
localData = data;
$bar.empty();
$.each(data,
function(i, data) {
var t = $('<option>', { value: data.artID, text: data.artCode });
$bar.append(t);
});
});
$bar.change(function() {
var v = $(this).val();
var filteredData = localData.filter(function(item) {
return item.artID == v;
});
if (filteredData.length) {
$("#artCenaProd").val(filteredData[0].artCenaProd);
}
});
});
Also if you are populating the Dropdown's options using the ajax call, no need to use the DropDownList helper method! Simply write HTML markup for a SELECT element
<SELECT name='bar'>
</SELECT>

Related

dropdown not populating after ajax call in mvc5 platform

Have a good day. I here because of I am suffering a problem. That is I am working with a cascade dropdown in a user controller. When I change the MotherCompany then Division will appear as per mothercompany. My Controller end code is working fine. But in Front End Dropdown is not populating. What I am doing wrong can Anybody help me please. ( Sorry for my BAD English )
controller code:
[HttpPost]
public JsonResult getDivision(int id)
{
var division = db.Divisions.Where(x => x.MotherCompanyId == id).ToList();
List<SelectListItem> listDivision = new List<SelectListItem>();
listDivision.Add(new SelectListItem { Text = "--Select State--", Value = "0" });
if (division != null)
{
foreach (var x in division)
{
listDivision.Add(new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
}
}
return Json(new SelectList(listDivision, "Value", "Text"), JsonRequestBehavior.AllowGet);
}
My Javascript here:
<script type="text/javascript">
$(document).ready(function () {
$("#MotherCompanyId").change(function () {
$("#divisionId").empty();
$.ajax({
url: '#Url.Action("getDivision")',
async: true,
type: "POST",
dataType: "json",
data: { id: $("#MotherCompanyId").val() },
success: function (data) {
$.each(data, function (i, val) {
$('select#divisionId').append(
$("<option></option>")
.attr("Value", val.Value)
.text(val.Text));
});
},
error: function (xhr) {
alert(" An error occurred.");
},
});
return false;
})
});
View: `
<div class="form-group MotherCompanyId">
#Html.LabelFor(model => model.MotherCompanyId, new { #class = "" })
#Html.DropDownList("MotherCompanyId", ViewBag.MotherCompanyId as SelectList, "Select a MotherCompany", htmlAttributes: new { required = "required", style = "display:none;width:100%;" })
#Html.StarkDropDownAjaxLink("/MotherCompany/Create", "AddMore", "")
</div>
<div class="form-group DivisionId">
#Html.LabelFor(model => model.DivisionId, new { #class = "" })
#Html.DropDownList("divisionId", new SelectList(string.Empty, "Value", "Text"), "--Select Division--", new { style = "display:none;width:100%;" })
#Html.StarkDropDownAjaxLink("/Division/Create", "AddMore", "")
</div>`

Unable retrieving data from server side using custom columns DataTable Plugin

i am trying to retrieving data by custom searching. my code work properly, but when i try to filter some data from the input box. the process, get stuck. Please can anyone tell me what I m forgotting ?
My JQuery
//this work fine retrieving data by only if i search using "Search box"
var dataTableInstance = $("#dataTable").DataTable({
bServerSide: true,
sAjaxSource: 'AccountingMovementsService.asmx/GetAccountingMovements',
"processing": true,
sServerMethod: 'POST',
columns: [
{
'data': 'Payment'
},
{
'data': 'Account',
},
{
'data': 'customer',
}
]
});
//here I make all input box under footer columns (work fine)
$('#dataTable tfoot th').each(function () {
var title = $(this).text();
$(this).html("<input type='text' placeholder='" + title + "' />");
});
//And here i get stuck processing ... and data not come
dataTableInstance.columns().every(function() {
var dataTableColumn = this;
$(this.footer()).find('input').on('keyup change', function () {
dataTableColumn.search(this.value).draw();
});
});
If i use NOT SERVER-SIDE all work fine
My c# code is
[WebMethod]
public void GetAccountingMovements(int iDisplayLength, int iDisplayStart, int iSortCol_0, string sSortDir_0, string sSearch)
{
int displayLength = iDisplayLength;
int displayStart = iDisplayStart;
int sortCol = iSortCol_0;
string sortDir = sSortDir_0;
string search = sSearch;
int filteredCount = 0;
var accountingTransactions = new List<AccountMovement>();
string cs = ConfigurationManager.ConnectionStrings["Sg4DevMaster"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetAccountingTransactions", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "DisplayLength",
Value = displayLength
});
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "DisplayStart",
Value = displayStart
});
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "SortCol",
Value = sortCol
});
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "SortDir",
Value = sortDir
});
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "Search",
Value = search
});
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
AccountMovement am = new AccountMovement();
filteredCount = Convert.ToInt32(rdr["totalCount"]);
am.payment = Convert.ToDouble(rdr["payment"]);
am.Account = Convert.ToDouble(rdr["account"]);
am.Customer = rdr["Customer"].ToString();
accountingTransactions.Add(am);
}
}
var result = new
{
iTotalRecords = GetAccountingMovementsTotalCount(),
iTotalDisplayRecords = filteredCount,
aaData = accountingTransactions
};
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(result));
}
All work fine using "the main search input box" in the DataTable Plugin, but it get stuck when put some data in one of custom input box placed in the footer
Thank for you time!
If you go to my GitHub https://github.com/bindrid/DataTablesServerSide take a look at the c# classes. That is how I take the parameters provided by DataTable and turn it into a usable c# object.
Also listed there is my web method that uses those classes.
Below is the DataTables logic, including your search stuff and it all works.
var table = $('#example').DataTable({
"processing": true,
"serverSide": true,
"rowCallback": function (row, data) {
if ($.inArray(data.employeeId, selected) !== -1) {
table.row(row).select();
}
},
"infoCallback": function (settings, start, end, max, total, pre) {
var api = this.api();
var pageInfo = api.page.info();
return 'Page '+ (pageInfo.page+1) +' of '+ pageInfo.pages + " ";
},
rowId:"employeeId",
"createdRow": function (row, data, dataIndex) {},
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
],
"select":"multi",
"lengthMenu": [5, [10, 15, 25, 50, -1], [5, 10, 15, 25, 50, "All"]],
"pageLength": 5,
"ajax": {
contentType: "application/json; charset=utf-8",
url: "wsSample.asmx/GetDTDataUnserializedObject",
type: "Post",
data: function (dtParms) {
// notice dtParameters exactly matches the web service
return JSON.stringify({ dtParameters: dtParms });
},
// Data filter is a part of ajax and lets you look at the raw
dataFilter: function (res) {
// You probably know by know that WebServices
// puts your data in an object call d. these two lines puts it
// in the form that DataTable expects
var parsed = JSON.parse(res);
return JSON.stringify(parsed.d);
},
error: function (x, y) {
debugger;
console.log(x);
}
},
order: [[0, 'asc']]
});
// add search boxes to footer
$('#example tfoot th').each(function () {
var title = $(this).text();
$(this).html("<input type='search' placeholder='" + title + "' />");
});
//And here i get stuck processing ... and data not come
table.columns().every(function () {
var dataTableColumn = this;
$(this.footer()).find('input').on('keyup change', function () {
dataTableColumn.search(this.value).draw();
});
});

apply tooltip on child grid in hierarchy kendo grid

I have 2 level of hierarchy kendo grid. As Child grid have unique name every time I am unable to get selected row Id and could not apply tooltip on change event of child grid.
Parent grid name= "AccountStatusgrid"
<script type="text/kendo" id="LocationsTemplate">
#(Html.Kendo().Grid<NOC.Entities.Location>()
.Name("AccountStatusgrid_#=AccountId#")
.Columns(column =>
{
column.Bound(c => c.LocationName).Title("Location Name").HeaderHtmlAttributes("style=align:center;").Width(100);
column.Template(#<text> </text>).ClientTemplate("<html><span>Device</span></html>").HeaderHtmlAttributes("style=align:center;").Title("Devices").Width(100);
for (int i = 0; i < Model.MockServiceHeaders.Count(); i++)
{
column.Bound(c => c.LocationStatus).Title(Model.MockServiceHeaders.ToList()[i].ServiceName.ToString()).Width(20).HtmlAttributes(new { title = " " });
}
})
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Single)
.Type(GridSelectionType.Cell))
.AutoBind(true)
.DataSource(source => source.Ajax()
.Model(model =>
{
model.Id(o => o.LocationId);
})
.ServerOperation(true)
.Events(events => events.Error("error_handler"))
.Read(read => read.Action("GetLocationData", "Account", new { AccountId = "#=AccountId#" }))
)
.Events(events => events.DataBound("Grid_onRowDataBound").Change("Grid_onCellChange_Locations"))
.ClientDetailTemplateId("DeviceTemplate")
.ToClientTemplate()
)
</script>
function Grid_onCellChange_Locations() {
var grid = $("AccountStatusgrid_#=AccountId#").data("kendoGrid");
var dataItem = grid.dataItem(grid.select().closest("tr"));
var Sel_accountId = dataItem.AccountId;
var Sel_loactionId = dataItem.LocationId;
var Sel_deviceId = dataItem.DeviceId;
var selected = $.map(this.select(), function (item) {
var index = $(item).index();
if (grid.columns[index - grid.dataSource._group.length] != undefined) {
ServiceName = grid.columns[index - grid.dataSource._group.length].title;
}
else
ServiceName = "";
Selectedservicestatus = $(item).text()
});
$("AccountStatusgrid_#=AccountId#").kendoTooltip({
filter: 'td[title]',
showOn: "click",
content: {
url: '#Url.Action("Tooltip", "Account")',
data: { accountId: Sel_accountId, locationId: Sel_loactionId, deviceId: Sel_deviceId, serviceName: ServiceName }
},
width: 290,
height: 360,
position: "right"
});
}
Currently $("AccountStatusgrid_#=AccountId#") is not accessible.
please let me know how can I get dataitem property of child grid and apply tooltip on child grid.
You can try below code for get child grid dataItem..
$("#grid").delegate(".details-button", "click", function(e) {
var row = $(this).closest("tr"),
grid = $(this).parents("[data-role=grid]").data("kendoGrid"); //gets child grid
var model = grid.dataItem(row);
console.log(model); //model contains the id
}
or use this code may be help you.
function expand(e) {
var dataItem = this.dataItem(e.node);
if (dataItem.hasChildren) {
var childItems = dataItem.children.data();
}
if you like my answer then don't forget to vote me..
You can apply a class to your child grid's cell that you want the tooltip on with a column attribute:
{ field: "MyColumn", title: "Ref #", attributes: { "class": "tooltip2" } },
Then define your tooltip using a filter on the class name:
mySubGrid.element.kendoTooltip({
filter: ".tooltip2",
position: "right",
content: "My tooltip."}).data("kendoTooltip");

How do I generate a treeView based on remote data using Kendo UI TreeView?

I have been reading ALL of the documentation on this and I still cannot get it to work.
I have a Web API which provides a JSON object. It's a list of 22 things. Just 22 lines of text.
I want to take these and form a TreeView. Each of these 22 strings will have items under them but I just want to get the first part working.
My first question is, how do I extract data from an API and populate a treeView with it?
On my main page, I have this:
<div id="treeView"></div>
On my JavaScript file I have this:
$("#treeView").kendoTreeView({
checkboxes: true,
dataSource: {
transport: {
read: {
url: "http://...",
dataType: "json"
}
}
}
});
When I try to run the page, I get "Request failed." [Retry]
If I open up a browser and go to this URL, data is returned fine as a JSON object.
What am I doing wrong here?
EDIT -
Code that is returning the JSON:
public List<string> getNotificationByUser(int id)
{
List<string> notificationTitles = new List<string>();
foreach (var notification in notifications)
{
notificationTitles.Add(notification.ToString());
}
return notificationTitles;
}
Ok! I've been able to reproduce your error. The question is that 22 lines of text are not a valid JSON.
Returning something like:
This
is
a
test
Is not a valid JSON.
But a valid JSON is not enough, you should return something like this:
[
{ "text": "This" },
{ "text": "is" },
{ "text": "a" },
{ "text": "test" }
]
I.e.: The result should be an array of objects where each object has a text field.
NOTE I know that it does not have to be called text but for simplicity I used it since it is the default value.
I figured out all of my answers:
function CreateNotificationTree(userId)
{
debugger;
var data = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/notifications/byuserid/" + userId,
contentType: "application/json"
}
},
schema: {
model: {
children: "notifications"
}
}
});
$("#treeview").kendoTreeView({
dataSource: data,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["notificationType", "NotificationDesc"],
select: treeviewSelect
});
function treeviewSelect(e)
{
var node = this.dataItem(e.node);
window.open(node.NotificationLink, "_self");
}
}
[HttpGet]
public List<Node> getNotifications(int id)
{
var bo = new HomeBO();
var list = bo.GetNotificationsForUser(id);
var notificationTreeNodes = (from GBLNotifications n in list
where n.NotificationCount != 0
select new NotificationTreeNode(n)).ToList();
var li = notificationTreeNodes.Select(no => new Node
{
notificationType = no.NotificationNode.NotificationType + " " + "(" + no.NotificationNode.NotificationCount + ")", notifications = bo.GetNotificationsForUser(id, no.NotificationNode.NotificationTypeId).Cast<GBLNotifications>().Select(item => new Notification
{
ID = item.NotificationId, NotificationDesc = item.NotificationDescription, Params = new List<NotificationParam>
{
new NotificationParam
{
ParamName = item.Param1, ParamVal = item.ParamValue1
},
new NotificationParam
{
ParamName = item.Param2, ParamVal = item.ParamValue2
},
new NotificationParam
{
ParamName = item.Param3, ParamVal = item.ParamValue3
},
new NotificationParam
{
ParamName = item.Param4, ParamVal = item.ParamValue4
},
new NotificationParam
{
ParamName = item.Param5, ParamVal = item.ParamValue5
},
},
ActionPageName = item.ActionPageName
}).ToList()
}).ToList();
li.ForEach(i => i.notifications.ForEach(x => x.SetNotificationLink()));
return li;
}

How to preselect items within a Fuel UX treeview?

so I've implemented the treeview of Fuel UX within my website. Whenever it's loaded, I need to reselect the items I want manually. Is there a possibility to preselect certain items after each reload?
Thanks in advance!
I was in the same situation since yesterday and could now solve the problem with the solution below. Just explaining that I used the methods present on the button "select nested Test Item 1" on this page. Here's the solution:
var preSelectFolder = function ($treeEl, folder, $parentEl) {
var $elParent = $parentEl || $treeEl;
if (folder.type == "folder") {
var $folderEl = $elParent.find("div.tree-folder-name").filter(function (_, treeFolder) {
return $(treeFolder).text() == folder.name;
}).parent();
$treeEl.one("loaded", function () {
$.each(folder.children, function (i, item) {
preSelectFolder($treeEl, item, $folderEl.parent());
});
});
$treeEl.tree("selectFolder", $folderEl);
}
else {
preSelectItem($treeEl, folder, $elParent);
}
};
var preSelectItem = function ($treeEl, item, $parentEl) {
var $elParent = $parentEl || $treeEl;
if (item.type == "item") {
var $itemEl = $elParent.find("div.tree-item-name").filter(function (_, treeItem) {
return $(treeItem).text() == item.name && !$(treeItem).parent().is(".tree-selected");
}).parent();
var itemId = $($itemEl).data() != null ? $($itemEl).data().id : "";
if (itemId == item.id)
$treeEl.tree("selectItem", $itemEl);
}
else if (item.type == "folder") {
preSelectFolder($treeEl, item, $elParent);
}
};
And in the event of 'loaded' I use this code:
element.on('loaded', function (e) {
angular.forEach(scope.items, function (item) {
preSelectItem($("#BuildTree"), item);
});
});
I use AngularJs so just replace "angular.forEach" for each function of Jquery and "scope.items" are items that should be pre-selected. In my case the items are in the following format:
[
{ name: 'Dir 1', type: 'folder', id: 'D1' },
{ name: 'Dir 2', type: 'folder', id: 'D2' },
{ name: 'Item 1', type: 'item', id: 'i1' },
{ name: 'Item 2', type: 'item', id: 'i2' }
]
Hope that helps.
If by manually, you mean you're actually clicking on the items again there should be a way to do this more programmatically.
I haven't tested it, but if you call $('#MyTree').tree('selectItem', $el) where $el is a .tree-item element, that should select the item.
It would be nice for your datasource to be able to tell the tree which items are selected. I see you've posted the feature request to https://fuelux.uservoice.com/forums/181290-general/suggestions/4097231-add-preselect-option-for-treeview which is great - anyone else reading this who agrees it would be useful should vote there.
I make if for ASP.NET MVC. I use a dynamic tree.
At first I received a route for selected item
[{
"id": 1, // parent category
"name": "Все категории",
}, {
"id": 56, // 1-st sub category
"name": "Для дома",
}, {
"id": 63, // item
"name": "Домашние растения",
}]
Then it need to switch off Async request for Ajax in dataSource function: 'async':false
This is all code:
#{
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string catRoute = jsonSerializer.Serialize(ViewBag.catRoute);
}
var catRoute = $.parseJSON('#Html.Raw(catRoute)'); // this is object of item route
function dynamicDataSource(openedParentData, callback) {
var childNodesArray = [];
$.ajax({
'type': 'post',
'url': '#Url.Action("getFuelUxTree", "Category", new { area = "Root" })',
'data': openedParentData,
'async':false // switch off ajax request
})
.done(function (data) {
childNodesArray = data;
lastTree = data;
callback({
data: childNodesArray
});
});
}
$('#categoryTree').tree({
dataSource: dynamicDataSource,
multiSelect: false,
folderSelect: false
});
// iterate all route items and open category
for (var i = 0; i < catRoute.length; i++) {
$('li#'+catRoute[i].id+' button', '#categoryTree').click();
}

Categories