Javascript populate Telerik MVC combobox from an array - c#

my application is MVC4; I am trying to populate a Telerik MVC using json, the result is an array; however I get only one item; here is my script:
function CheckWord() {
var wordtocheck = $('#Cword').val();
alert(wordtocheck);
$.ajax({
url: '/Home/CheckWord',
type: 'POST',
data: {
cword: wordtocheck
},
success: function (data) {
for (var i = 0; i < data.array.length; ++i) {
var myString = data.array[i];
var mySplitResult = myString.split("-->");
var hms = mySplitResult[0];
var a1 = hms.split(',');
var a2 = a1[0];
var a = a2.split(':');
var start = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var hms1 = mySplitResult[1];
var b1 = hms1.split(',');
var b2 = b1[0];
var b = b2.split(':');
var end = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]);
var dropDownList = $('#ComboBox').data('tComboBox');
dropDownList.dataBind([
{ Text: start[i] + "-" + end[i], Value: start[i] + "-" + end[i] }]);
dropDownList.select(0);
}
},
error: function () {
}
});
When I add [i] after start and end, I get undefined! without [i] I get the correct value however just one item. Would appreciate your suggestions, thanks in advance.

Hope the following link will help
http://www.telerik.com/community/forums/aspnet-ajax/mvc/radcombobox-populate-on-client-side.aspx
Here you can see
<telerik:RadComboBox ID="radProject" runat="server" Skin="Default" Width="300px"
EnableLoadOnDemand="true" Filter="Contains" OnClientItemsRequesting="getProjects"
EmptyMessage="Select Project" />
in the above code EnableLoadOnDemand is set to true and Filter is set to contains and the event bound to OnClientItemsRequesting.
function getProjects(sender, args) {
itemsRequesting(sender, args);
$.getJSON(
'<%= Url.Action("GetProjects", "Capital") %>',
{ facility: GetFacility().get_value() },
function(data) {
fillCombo(sender, data);
sender.highlightAllMatches(sender.get_text());
});
}
the above javascript method is executing a ajax call using get JSON with parameters and the sub methods fillCombo is filling the combo box.
// Use this for all of your RadComboBox to populate from JQuery
function fillCombo(combo, result) {
combo.clearItems();
var items = result.d || result;
// This just lets your users know that nothing was returned with their search
if (items.length == 0) {
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
comboItem.set_text("Nothing found");
comboItem.set_value("null");
combo.get_items().add(comboItem);
combo.set_text("");
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
comboItem.set_text(item.Text);
comboItem.set_value(item.Value);
combo.get_items().add(comboItem);
}
}
Now in order to cancel the default behavious of RADComboBox you can use the following code
// This cancels the default RadComboBox behavior
function itemsRequesting(sender, args) {
if (args.set_cancel != null) {
args.set_cancel(true);
}
if (sender.get_emptyMessage() == sender.get_text())
sender.set_text("");
}
I hope the above solution will solve your problem

Here is how I solved the problem:
function CheckWord() {
var wordtocheck = $('#Cword').val();
alert(wordtocheck);
$.ajax({
url: '/Home/CheckWord',
type: 'POST',
data: {
cword: wordtocheck
},
success: function (data) {
var listData = [];
for (var i = 0; i < data.array.length; ++i) {
var myString = data.array[i];
var mySplitResult = myString.split("-->");
var hms = mySplitResult[0];
var a1 = hms.split(',');
var a2 = a1[0];
var a = a2.split(':');
var start = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var hms1 = mySplitResult[1];
var b1 = hms1.split(',');
var b2 = b1[0];
var b = b2.split(':');
var end = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]);
listData[i] = { Text: myString, Value: start };
}
var dropDownList = $('#ComboBox').data('tComboBox');
// debugger;
dropDownList.dataBind(listData);
dropDownList.select(0);
},
error: function () {
}
});
}
Hope this will be helpful to others.

Related

Print the Remaining Session Time to View in Real-Time in ASP.NET

Is it possible to show the remaining session time in View in real-time when logged in ASP.NET MVC project? I didn't add any code to the question because I didn't come across any solution during my research.
I would do this in 2 steps, first pass the timeout value using a partial, so it can be reused. For e.g. read it from your Web.Config etc and pass it.
Then inside your view, you can add this script and adapt/modify the values.
#functions {
public int PopupShowDelay {
get { return 60000 * (Session.Timeout - 1); }
}
}
<script type="text/javascript">
window.SessionTimeout = (function() {
var _timeLeft, _popupTimer, _countDownTimer;
var stopTimers = function() {
window.clearTimeout(_popupTimer);
window.clearTimeout(_countDownTimer);
};
var updateCountDown = function() {
var min = Math.floor(_timeLeft / 60);
var sec = _timeLeft % 60;
if(sec < 10)
sec = "0" + sec;
document.getElementById("CountDownHolder").innerHTML = min + ":" + sec;
if(_timeLeft > 0) {
_timeLeft--;
_countDownTimer = window.setTimeout(updateCountDown, 1000);
} else {
window.location = "Home/TimeOutPage";
}
};
var showPopup = function() {
_timeLeft = 60;
updateCountDown();
ClientTimeoutPopup.Show();
};
var schedulePopup = function() {
stopTimers();
_popupTimer = window.setTimeout(showPopup, #PopupShowDelay);
};
var sendKeepAlive = function() {
stopTimers();
ClientTimeoutPopup.Hide();
SessionTimeout.schedulePopup();
};
return {
schedulePopup: schedulePopup,
sendKeepAlive: sendKeepAlive
};
})();
</script>
#using (Html.BeginForm()) {
<p>
A timeout warning popup will be shown every #(Session.Timeout - 1) min.
</p>
#Html.Partial("TimeoutPartial")
}

Deserialization JSON time MVC

i try to get a time from Ajax request dateType json .
the result i get is :
/DATE(1436688000000)/
heres my code :
view:
<div class="col-sm-8">
#Html.DropDownListFor(model => model[i].MovieShowTime.Single().MovieID, SelectMovieID, "Select Movie", new { id = "MovieName", name = "MovieName" })
#Html.DropDownListFor(x => x[i].MovieShowTimeID, Enumerable.Empty<SelectListItem>(), "--Loading Value--", new { id = "ShowTime", name = "ShowTime" })
#Html.ValidationMessageFor(model=>model[i].MovieShowTimeID)
</div>
controller :
public JsonResult GetShowTime(int? MovieID)
{
var data = (from m in db.MovieShowTimes
where m.MovieID == MovieID
select new
{
id = m.MovieShowTimeID,
name = m.ShowTime
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
ajax : .
$(function () {
$('#MovieName').change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetShowTime", "TimeScreening")',
data: { MovieID: $('#MovieName').val() },
dataType : 'json',
success: function (data) {
$('#ShowTime').html('');
//alert(ChangeDateFormat("\/Date(1319266795390+0800)\/"));
$.each(data, function (id, option) {
var name = ChangeDateFormat(option.name)
$('#ShowTime').append($('<option></option>').val(option.id).html(option.name));
});
},
error: function (xhr, ajaxOptions, thrownEror) {
alert("False" + xhr +"..."+ ajaxOptions +"... "+ thrownEror);
}
});
});
});
i see the threds about convert form json to C# datetime but none of them have resolved the problem .
follow by this post:
JSON-Serialization-and-Deserialization-in-ASP-NET this jave me the closet answer , but this in date.
code:
function ChangeDateFormat(jsondate) {
jsondate = jsondate.replace("/Date(", "").replace(")/", "");
if (jsondate.indexOf("+") > 0) {
jsondate = jsondate.substring(0, jsondate.indexOf("+"));
}
else if (jsondate.indexOf("-") > 0) {
jsondate = jsondate.substring(0, jsondate.indexOf("-"));
}
var date = new Date(parseInt(jsondate, 10));
var month = date.getMonth() + 1 < 10 ?
"0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return date.getFullYear() + "-" + month + "-" + currentDate;
}
this answer : Format a Microsoft JSON date really no ugly parsing but this gave me a datetime.now and no close to time.
this answer : ASP.NET MVC JsonResult Date Format is the same.
and this artical is good but the same.. dates-and-json
so.. what i need to do?
I have this set of functions
// START Datetime Converters
function DateConverter(date) {
var aux = null;
if (date != null) {
aux = date.substring(6);
aux = aux.substring(0, aux.indexOf(')'));
}
return aux != null ? getISODate(new Date(parseInt(aux))) : "";
}
function DatetimeConverter(date) {
var aux = null;
if (date != null) {
aux = date.substring(6);
aux = aux.substring(0, aux.indexOf(')'));
}
return aux != null ? getISODateTime(new Date(parseInt(aux))) : "";
}
function getISODate(d) {
// padding function
var s = function (a, b) { return (1e15 + a + "").slice(-b) };
// default date parameter
if (typeof d === 'undefined') {
d = new Date();
};
// return ISO datetime
return zeroPad(d.getDate(), 2) + '/' +
zeroPad(s(d.getMonth() + 1, 2), 2) + '/' +
zeroPad(d.getFullYear(), 4);
}
function getISODateTime(d) {
// padding function
var s = function (a, b) { return (1e15 + a + "").slice(-b) };
// default date parameter
if (typeof d === 'undefined') {
d = new Date();
};
// return ISO datetime
return zeroPad(d.getDate(), 2) + '/' +
zeroPad(s(d.getMonth() + 1, 2), 2) + '/' +
zeroPad(d.getFullYear(), 4) + " " +
zeroPad(d.getHours(), 2) + ":" +
zeroPad(d.getMinutes(), 2) + ":" +
zeroPad(d.getSeconds(), 2);
}
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
// END Datetime Converters
Example: In a table where i show the CreatedDate:
{
"mRender": function (oAux, oType, oData) {
return DateConverter(oData.CreatedDate);
},
},
If you want Date and Time just use DatetimeConverter
What i'm doing
Inside the function DateConverter and DateTimeConverter i catch the number without the \DATE... like "1436688000000".
Then inside the getISODate, in the first line:
var s = function (a, b) { return (1e15 + a + "").slice(-b) };
Is a padding function. Where the day 2 will become "02" if you use it like:
s(d.getDate(), 2)
If the date that the action returns is null or invalid:
if (typeof d === 'undefined') {
d = new Date();
};
The other padding function is zeroPad that does what the function s() does but doesn't remove the left numbers, example:
var a = 3000;
var sA = s(3000, 2);
var zpA = zeroPad(3000, 2);
sA will become "00" while zpA will keep "3000"
PS: I can't remember why i used s function... i think that i forgot to delete it after creating zeroPad.

How to get value from list string?

The return result of string list is :
var result= "1,red,2,blue,3,green,4,orange";
I want to use a loop and get result like 1,2,3,4 and red,blue,green,orange
My code is as below.
I got the error in split.
Object does not support for split().
I am using jquery 1.10.1 .
$.ajax({
type: "GET",
url: "/_vti_bin/userService/myservice.svc/GetUserListForMentionSign?query" + query,
async: false,
dataType: "JSON",
cache: false,
processdata: true,
success: function (result) {
data = result;
//arrary
var resultArray = data.Split(',');
var id = new Array(), name = new Array();
$.each(resultArray, function (index, value) {
if (isNaN(value)) {
name.push(value);
alert(name.push(value));
}
else {
id.push(value);
}
});
Here is the web service for c#.
public List<string> GetUserListForMentionSign(string username)
{
List<User> UserList = new List<User>();
List<string> returnvalue=new List<string>();
try
{
string returnstring = string.Empty;
DataTable dt = null;
dt = Library.Helper.FindUser(username, 200);
foreach (DataRow dr in dt.Rows)
{
if (dr["Title"].ToString() != "Person.aspx") // those user without the name
{
User user = new User();
user.id = dr["ID"].ToString();
user.name = dr["Name"].ToString();
UserList.Add(spuser);
}
}
}
catch (Exception ex)
{
}
return UserList.Select(a=>new[]{ a.name.ToString(),a.id.ToString()}).SelectMany(a=>a).ToList();
}
You can use jQuery map function to create 2 different arrays containing even and odd indexed values and manipulate it
var result = "1,red,2,blue,3,green,4,orange";
var arr=result.split(',');
var odd = jQuery.map( arr, function(n,i){
return i%2 ? n : null;
});
var even = jQuery.map( arr, function(n,i){
return i%2 ? null : n;
});
Try this : Use .split() to convert string into array and then iterate array. Inside loop check if value is number of not using isNaN() and push values to respective array.
var result= "1,red,2,blue,3,green,4,orange";
var resultArray = result.split(",");
var numberArray = new Array(), colorArray = new Array();
$.each(resultArray , function( index, value ) {
if(isNaN(value))
colorArray.push(value);
else
numberArray.push(value);
});
alert(colorArray.toString());
alert(numberArray.toString());
try
var result = "1,red,2,blue,3,green,4,orange";
var splitValue = result.split(",");
var num = [];
var str = [];
for (var i in splitValue) {
if (i % 2 === 0) {
num.push(splitValue[i]);
} else {
str.push(splitValue[i]);
}
}
console.log(num);
console.log(str);
In C language I have implemented like this.
Logic: input is parsed to split num&strings and stored to different array. At the end result array is printed.
int main()
{
char *str, result []= "1,red,2,blue,3,green,4,orange";
char *p, *p1;
char num[10], i=0;
char name[10][15], j=0,k;
str =result;
while (1)
{
p= strchr (str, ',');
if(!p1)
break;
num [i]=atoi (p-1) ;
i++;
p1= strchr (p+1, ',');
if(!p1){
strcpy ( name[j], p+1);
j++;
break;
}
p1[0]='\0';
strcpy ( name[j], p+1);
j++;
str=p1+1;
}
for (k=0; k<i; ++k){
printf ( "%d ", num[k]);
}
printf ("\n");
for (k=0; k<j; ++k){
printf ( "%s ", name[k]);
}
printf ("\n");
}
var result= "1,red,2,blue,3,green,4,orange";
string[] arr = result.Split(',');
int[] num;
string[] text;
foreach(var i in arr)
{
int cont;
if (int.TryParse(i, out cont) == false)
text[] = i;
else
num[] = cont;
}
or loop manually
for(int i = 0; i < arr.lenght; i++)
{
int cont;
if (int.TryParse(arr[i], out cont) == false)
text[i] = i;
else
num[i] = cont;
}
note : splitting from server side for C#.

How to load a nested JSON / C# array into view model? using Knockout, jQuery

SuperNoob here, trying to load varying multiple "Options" either as a string[] or object, to a "Product" that can be added to a shopping cart using Knockout: (working from John Papa's PluralSight Knockout Change Tracking example)
Here is the view:
<div>
<span>OptionsArray: </span>
<ul data-bind="foreach: optionsArray">
<li data-bind="text: $data"></li>
</ul>
</div>
Here is the JSON converted into C#:
{Id = 4, ModelId = 1, SalePrice = 1.00, ListPrice = 1.00, Rating = 5, Photo = "smallCoffee.jpg", CategoryId = 1, ItemNumber = "smallCoffee", Description = "Small Coffee", Model = new Model(){ Name = "Small Coffee", Brand = "Tim Hortons", Id = 1 }, Category = drinkCat, Options = new Options(){Name = "Sugar"}, OptionsArray = new string[]{"Sugar", "Cream"}}
This javascript function works, loading json into an "products" array of Products, except I can't get it to iterate through varying multiple options for each product.
Here is the function part of the view model:
loadProductsCallback = function (json) {
my.vm.tracker().markCurrentStateAsClean();
$.each(json, function (i, p) {
products.push(new my.Product(selectedProduct)
.id(p.Id)
.salePrice(p.SalePrice)
.photo(p.Photo)
.category(new my.Category()
.id(p.Category.Id)
.name(p.Category.Name)
)
.model(new my.Model()
.id(p.Model.Id)
.name(p.Model.Name)
.brand(p.Model.Brand)
)
.options(new my.Options()
.name(p.Options.Name)
)
.description(p.Description)
.rating(p.Rating)
.stateHasChanged(false);
$.each(p.OptionsArray, function(i, o) { p.optionsArray.push(o);});
);
});
And here is the Product object that is taking all the data:
Product = function (selectedItem) {
var self = this;
self.id = ko.observable();
self.salePrice = ko.observable();
self.photo = ko.observable();
self.model = ko.observable();
self.options = ko.observable();
self.optionsArray = ko.observableArray(["1", "2"]);
self.category = ko.observable();
self.description = ko.observable();
self.rating = ko.observable();
self.isSelected = ko.computed(function () {
return selectedItem() === self;
});
self.isDrink = ko.computed(function () {
return this.category() ? this.category().id() === 1 : false;
}, self),
self.isFood = ko.computed(function () {
return this.category() ? this.category().id() === 4 : false;
}, self),
self.shortDesc = ko.computed(function () {
return this.model() ? this.model().name() : "";
}, self),
self.opt = ko.computed(function () {
return this.options() ? this.options().name() : "";
}, self),
self.optQty = ko.computed(function () {
return this.options() ? this.options().qty() : "";
}, self),
self.photoUrl = ko.computed(function () {
return photoPath + this.photo();
}, self),
self.rating.subscribe(function () {
this.stateHasChanged(true);
}, self),
self.stateHasChanged = ko.observable(false);
};
The loadProductsCallback function works fine except for the part adding the nested OptionsArray in. I've tried a nested $.each functions and just simply .optionsArray(p.OptionsArray).
There is a lot more code: I hope that this is enough to make sense.
Dear Stackers, how can I properly load the OptionsArray into the Products object using this function?
Not sure I'm quite understanding your code but here goes.
You are new'ing up a product then trying to loop through a collection and map it to options. Except you are pushing the results to the source object.
What about this.
loadProductsCallback = function (json) {
my.vm.tracker().markCurrentStateAsClean();
$.each(json, function (i, p) {
var newProduct = new my.Product(selectedProduct)
.id(p.Id)
.salePrice(p.SalePrice)
.photo(p.Photo)
.category(new my.Category()
.id(p.Category.Id)
.name(p.Category.Name)
)
.model(new my.Model()
.id(p.Model.Id)
.name(p.Model.Name)
.brand(p.Model.Brand)
)
.options(new my.Options()
.name(p.Options.Name)
)
.description(p.Description)
.rating(p.Rating)
.stateHasChanged(false);
$.each(p.OptionsArray, function(i, o) {
newProduct.optionsArray.push(o);
});
products.push(newProduct);
});
}
Hope this helps.

How to call Html.RenderAction() with parameters declarated in jscript?

I have a javascript in *.cshtml file
$(function () {
sliderDiv.slider({
range: true,
min: minVal,
max: maxVal,
values: [minVal, maxVal]
});
sliderDiv.bind("slidechange", function (event, ui) {
var d = "min=" + ui.values[0] + "&max=" + ui.values[1];
$.ajax({
type: "POST",
url: '#Url.Action("Update", "Default")',
data: d,
success: function (result, ajaxObj) {
alert('ok');
alert(result.min + " - " + result.max);
$("#ajaxresult").html('#{Html.RenderAction("Update", "Default");}');
},
error: function (ajaxObj, message, exceptionObj) { alert('no'); }
});
});
}
And Controller:
public ActionResult Update(int? min, int? max)
{
if(min == null) min = 1;
if(max == null) max = 1;
var s = new SliderModel()
{
min = (int)min * 1000,
max = (int)max * 1000
};
return new JsonResult
{
Data = s,
ContentEncoding = Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
ContentType = "json"
};
}
I want to use this line
$("#ajaxresult").html('#{Html.RenderAction("Update", "Default");}');
to send ui.values[0] and ui.values[1] as min and max parameters to Html.RenderAction("Update", "Default")
Something like $("#ajaxresult").html('#{Html.RenderAction("Update", "Default", new {min = ui.values[0], max = ui.values[1]});}');
How can I do something like that???
var url = '#Url.Action("Update", "Default")';
url += '/?min=' + ui.values[0] + '&max=' + ui.values[1];
$("#ajaxresult").load(url);
load docs:
Description: Load data from the server and place the returned HTML into the matched element.

Categories