Knockout-Kendo dropdownlist Ajax observableArray get selected item name - asp.net-mvc

My application is MVC 5, I use the following Knockout-kendo dropdown list:
<input data-bind="kendoDropDownList: { dataTextField: 'name', dataValueField: 'id', data: foodgroups, value: foodgroup }" />
var ViewModel = function () {
var self = this;
this.foodgroups = ko.observableArray([
{ id: "1", name: "apple" },
{ id: "2", name: "orange" },
{ id: "3", name: "banana" }
]);
var foodgroup =
{
name: self.name,
id: self.id
};
this.foodgroup = ko.observable();
ko.bindingHandlers.kendoDropDownList.options.optionLabel = " - Select -";
this.foodgroup.subscribe(function (newValue) {
newValue = ko.utils.arrayFirst(self.foodgroups(), function (choice) {
return choice.id === newValue;
});
$("#object").html(JSON.stringify(newValue));
alert(newValue.name);
});
};
ko.applyBindings(new ViewModel());
It works great, thanks to this answer Knockout Kendo dropdownlist get text of selected item
However when I changed the observableArray to Ajax:
this.foodgroups = ko.observableArray([]),
$.ajax({
type: "GET",
url: '/Meals/GetFoodGroups',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.foodgroups(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
Controller - get the table from ms sql server:
public JsonResult GetFoodGroups()
{
var data = db.FoodGroups.Select(c => new
{
id = c.FoodGroupID,
name = c.FoodGroupName
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
I get this error when I alert the item name
Unable to get property 'name' of undefined or null reference
What is the difference between hardcoding the array items from using Ajax.

The 'id' field has string datatype in hard coded array.
The 'id' field has number datatype in ajax array.
.
So, the 'id' field has different datatypes in both arrays. However in-condition you have used === operator so it checks value as well as datatype.
For ajax array value is same but its datatype is different so its not returning result.
Let me know if any concern.

Related

ajax other parameter is null?

why my other paramter is null. "date" and "ids" is null while my "postedFile" and "amount" has a data. but when i try to removed "postedFile" parameter. the ids and date has a value. and it works fine. but i need the postedfile parameter
My Script
var ids = [];
function add(id, isChecked) {
if (isChecked) {
ids.push(id);
}
else {
var i = ids.indexOf(id);
ids.splice(i, 1);
}
}
function saveSelected() {
//var shipmentId = $('#c-shipment-id').val();
var date = $('#Date').val();
var amount = $('#Amount').val();
//var ImageFile = $('#imageUploadForm').val();
$('#imageUploadForm').on("change", function () {
var formdata = new FormData($('form').get(0));
CallService(formdata);
});
function CallService(postedFile) {
$.ajax({
url: '#Url.Action("index", "payment")',
type: 'POST',
data: { ids: ids, amount: amount, date: date, postedFile: postedFile },
cache: false,
processData: false,
contentType: false,
traditional: false,
dataType:"json",
success: function (data) {
alert("Success");
}
});
}
}
My Controller
public ActionResult Index(int?[] ids, decimal? amount, DateTime? date, HttpPostedFileBase postedFile)
{
return View();
}
As the comments above, I guess you could try to pass all the values with parameters, instead of the variables, like: CallService(formdata, ids, amount, date). It may works.
To answer your secondary question - Fetch all selected IDs in a table with a checkbox column:
Fisrt, add the ID into the checkbox's ID in the view, e.g.:
foreach (var m in Model.Data)
{
row++;
<tr class="#(row % 2 == 0 ? "alter" : "")">
<td class="first">
<input id="chk_#m.ID" type="checkbox" onclick="js_selone(this)" />
</td>
...
Then, Create a JS method getSelVal() to fetch all selected IDs and return an combined string with ,, e.g.: 1,2,3.
$.fn.getSelVal = function () {
for (var e = "", t = $("input[type=checkbox]", this), n = 0; n < t.length; n++) t[n].checked && (e += "," + js_getid(t[n].id));
return e.Trim(",");
}
Finally, you can call the method and pass the ids or ids.toString().split(',') to AJAX request:
ids = $('.table td').getSelVal().toString().split(',');
CallService(formdata, ids, amount, date)
function CallService(postedFile, ids, amount, date) {
$.ajax({
url: '#Url.Action("index", "payment")',
type: 'POST',
data: { ids: ids, amount: amount, date: date, postedFile: postedFile },
cache: false,
processData: false,
contentType: false,
traditional: false,
dataType:"json",
success: function (data) {
alert("Success");
}
});

Update Kendo Grid based On Search Form Post

I've been doing alot of searching but haven't found a clear answer for this. I have a set up textboxes that and a submit button and a Kendo UI grid. I want to post the data to the grid's datasource so that it will return the results based on the criteria. I am not using the MVC wrappers.
EDIT:
I've gotten closer but I can't seem to get the datasource to send the post data when I click submit. I've debugged and in my $("#fmSearch").submit it is hitting the jquery plugin and I've confirmed that it is converting the form data to JSON properly, but it seems as though it it not sending the updated information to the server so that the Action can read it.
Javascript
var dsGalleryItem = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Content("~/Intranet/GalleryItem/SearchGalleryItems")',
type: "POST",
data: $("#fmSearch").serializeFormToJSON(),
cache: false
}
},
schema: {
model: {
id: "galleryItemID",
fields: {
galleryItemID: {
nullable: true
},
imageName: {},
collectionName: {},
categoryName: {},
lastUpdatedOn: { type: "date" }
}
}
}
});
var gvResults = $("#gvResults").kendoGrid({
autoBind:false,
columns: [{
field: "imageName",
title: "Item Name",
template: "<a href='#Url.Content("~/Intranet/GalleryItem/Details/")#=galleryItemID#'> #=imageName#</a>"
}, {
field: "collectionName",
title: "Collection"
}, {
field: "categoryName",
title: "Category"
}, {
field: "lastUpdatedOn",
title: "Last Updated",
format: "{0:M/d/yyyy}"
}
],
selectable: "row",
change: onRowSelect,
dataSource: dsGalleryItem
});
$("#fmSearch").submit(
function (event) {
event.preventDefault();
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
});
MVC Action
[HttpPost]
public JsonResult SearchGalleryItems(string keyword, int? category, int? collection, DateTime? startDate, DateTime? endDate)
{
var galleryItemList = (from g in db.GalleryItems
//where g.imageName.Contains(keyword)
select new GalleryItemViewModel
{
galleryItemID = g.galleryItemID,
imageName = g.imageName,
collectionName = g.collection.collectionName,
categoryName = g.category.categoryName,
lastUpdatedOn = g.lastUpdatedOn
});
var galleryItemCount = Json(galleryItemList.ToList());
return Json(galleryItemList.ToList()); ;
}
The action is not setup to retrieve different data right now I just need to know how to connect the form to the grid.
Found the problem. I had this:
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
It needed to be this:
dsGalleryItem.read($("#fmSearch").serializeFormToJSON());

Autocomplete in Jqgrid returns Data from Server but dont know to put in View

This is my first post. stackoverflow is a wonderful place for developers. Here is my issue.
I am trying to use Autocomplete in JqGrid Edit Form. i successfully retrieved data from server using ajax call but dont know how to display it in the view. below is my code.
FrontEnd Code:
colModel :[
{name:'prf_articlename', index:'prf_articlename', width:90, editable:true, edittype:'text',
editoptions: {
dataInit:function(e){
$(e).autocomplete({
source: function(request, response,term) {
var param = request.term;
$.ajax({
url: '/Myelclass/AutoCompleteServlet.do?term='+param+"&action="+"artname",
success: function (data) {
response($.map(data, function(item) {
return {
label: item.label,
};
}));//END Success
},
});//END AJAX
},
minLength: 2,
});//END AUOTOCOMPLETE
}//END Dataint
}//END Dataint
},
BackEnd Code:
String term = request.getParameter("term");
List<AutoComplete> articlelist = prfbo.getArticleNameinEditGrid(term);
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
Any one help on this???
This is what I personally use in my project:
Inside colModel:
dataInit: function (elem) { NameSearch(elem) }},
The function:
function NameSearch(elem) {
$(elem).autocomplete({ source: '/Controller/NameSearch',
minLength: 2, autosearch: true,
select: function (event, ui) {
$(elem).val(ui.item.value);
$(elem).focus().trigger({ type: 'keypress', charCode: 13 });
}
})//$(elem).autocomplete
$(elem).keypress(function (e) {
if (!e) e = window.event;
if (e.keyCode == '13') {
setTimeout(function () { $(elem).autocomplete('close'); }, 500);
return false;
}
})//$(elem).keypress(function (e){
} //function NameSearch(elem) {
I'm also dealing with an Enter key press as well in the above function.
here is the complete code for my Autocomplete in jqgrid Edit form..
colModel :[
{name:'name', index:'name', width:90, align:'center', editable:true, hidden: false, edittype:'text',
editoptions:{
dataInit:function (elem) {
$(elem).autocomplete({
minLength: 2,
source: function(request, response,term) {
var param = request.term; //values we enter to filter autocomplete
$.ajax({
url: "myurl",
dataType: "json",
type:"GET",
success: function (data) {
response($.map(data, function(item) {
return {
//can add number of attributes here
id: item.id,
shform: item.shortform,
value: item.name,
clr : item.color, //here apart from name and id i am adding other values too
size: item.size,
remar:item.remarks,
subs: item.subs,
selec:item.selec ,
};
}));//END Response
},//END Success
});//END AJAX
},
select: function( event, ui ) {
// setting values to textbox in jqgrid edit form based on selected values
$('#textbox1').val(ui.item.id);
$('#textbox2').val(ui.item.shform);
$('#textbox3').val(ui.item.clr);
$('#textbox4').val(ui.item.size);
$('#textbox5').val(ui.item.sizeremar);
$('#textbox6').val(ui.item.subs);
$('#textbox7').val(ui.item.selec);
$('#textbox8').val(ui.item.selp);
}
});
$('.ui-autocomplete').css('zIndex',1000); // if autocomplete has misalignment so we are manually setting it
}
}, editrules :{required : true},
formoptions:{rowpos: 1, colpos: 2}
},
........
]
server code :
String term = request.getParameter("term");
List<ArticleDetails> articlelist = prfbo.getPrfArticleName(term); //DB call via BO and DAO class
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
hope some one find it useful.

dropdownlistfor selected value list item possible?

I'm currently working in ASP.NET MVC 4 and I'm trying to do something special here.
Here's the code I currently have for my dropdownlist:
#Html.DropDownListFor(m => m.SourceList, new SelectList(Model.SourceList, "Id", "Name", new { id = "SourceList" }))
Now this works, but it's pretty dumb what I'm doing here. In my back-end I query again to get the entire model from the id I just selected.
What I need is not the Id of the selected model, but the entire model. Is there any way of doing this?
My current JQuery callback:
$.ajax({
url: '#Url.Action("SetLicensesAfterSourceChange", "Permission")',
type: 'POST',
dataType: 'json',
contentType: 'application/json;',
data: JSON.stringify({ "Id" : selectedStartSourceId, "sourceList" : jsonSourceList }),
success: function (result) {
//Do stuff here
}
});
What I want to be able to do:
$.ajax({
url: '#Url.Action("SetLicensesAfterSourceChange", "Permission")',
type: 'POST',
dataType: 'json',
contentType: 'application/json;',
data: "selectedModel" = modelFromDropDownList,
success: function (result) {
//Do stuff here
}
});
It's probably a bit far-fetched, but you could create a Javascript array representation of your entire list of source objects, and use jQuery and a simple html select ( with the id & name for the options) to retrieve the item from the array.
<script>
var items = [
{
name = "een",
value = "1",
propertyX = "hallo"
},
{
name = "twee",
value = "2",
propertyX = "wereld"
}
];
$("#ddlselect").change(function(e) {
e.preventDefault();
var selectedOptionVal = $(this).val();
var found = null;
foreach (item in items)
{
if (!found && item.value == selectedOptionVal)
found = item;
}
// use found if set
if (found)
{
}
});
</script>
<select id="ddlselect">
<option value="">-- kies --</option>
<option value="1">een</option>
<option value="2">twee</option>
</select>

railsAutocomplete.select not working when option is selected throgh down arrow

I am using rails3-jquery-autocomplete for autocomplete functionality but when I select through mouse autocomplete works but if I select through keyboard down and arrow and click enter its not working I am having following code. What I am missing
$(".text_field_title").live("focusout",function(){
var name = $(this).attr("name");
var value = $(this).val();
var activity_id = $(this).attr("rel")
var practice_plan_id = $(this).attr('practice_plan_id');
$("#"+activity_id+"_title").bind('railsAutocomplete.select',function(event,data){
var data = [
{
name : name,
value : value
},
{
name : "activity_id",
value : activity_id
},
{
name :"fav_id",
value : data.item.id
}
];
$.ajax({
type: 'POST',
url: 'myurl',
data: data,
dataType: "script"
});
});
});

Resources