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

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.

Related

How to paginate in angular to display that i have reached the end of the blog?

If I click on loadnextPosts and the pageno exceeds the pagesize, it shouldn't load any posts or it should alert that I have reached the last page. I do not know the logic for it to work. When I click on loadnextposts, it just keeps on incrementing the pagesize and when the number of posts is exceeded it keeps on incrementing. I want it to alert me that I have reached the end of the posts.
Thank you
.controller('blogController', function ($http, user, $scope, getAllTurtles, $route) {
var vm = this;
var pageno = 1;
var pagesize = 9;
getData(pageno, pagesize);
function getData(pageno, pagesize) {
$http({
url: "../Services/svBlogPost.asmx/GetAllBlogPost2",
method: "get",
params: { pn: pageno, ps: pagesize }
}).then(function (response) {
$scope.ab = response.data;
})
};
vm.loadNextPosts = function () {
pageno += 1;
getData(pageno, pagesize);
//pageno += 1;
//if (pageno >= pagesize) {
// //pageno += 1;
// getData(pageno, pagesize);
//}
//else {
// alert('reached the last page');
// //$("#loadNextPosts").prop('');
//}
}
})
function getData(pageno, pagesize) {
$http({
url: "../Services/svBlogPost.asmx/GetAllBlogPost2",
method: "get",
params: { pn: pageno, ps: pagesize }
}).then(function (response) {
$scope.ab = response.data;
})
};
$scope.btnSearch = function () {
if (vm.ddlBlogKeyword == undefined) {
//do nothing
getData(pageno, pagesize);
}
else {
$http({
url: "../Services/svBlogPost.asmx/SelectByKeyword2",
method: "get",
params: { k: vm.ddlBlogKeyword }
}).then(function (response) {
$scope.ab = response.data;
});
}
}
vm.loadNextPosts = function () {
pageno += 1;
getData(pageno, pagesize);
}
})

Draw a line chart dynamically using sql server database using highchart.js

Not able to generate dynamic line chart with x-axis and series dynamically
I want month wise count for different destination.
I have done like this
function GetDestinationData() {
$.ajax({
async: false,
type: "POST",
url: "DataAnalysis.aspx/getDestination",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess1_,
error: OnErrorCall1_
});
}
function OnSuccess1_(response) {
var Xaxis = [];//skapa tre olika array
var dataseries = [];
for (var i = 0; i < response.d.length; i++) {
var items = response.d[i];
var XcategoreisItem = items.Month;
var seriesData = items;
if ($.inArray(XcategoreisItem, Xaxis) == -1) {
Xaxis.push(XcategoreisItem);
}
dataseries.push(seriesData);
// console.log(dataseries);
}
drawLineChart(Xaxis, dataseries);
}
function drawLineChart(Xaxis, dataseries) {
//categories = seriesData.map(function (a) { return a.x; });
//categories = categories.filter(function (v, i) { return categories.indexOf(v) == i; });
var chart = Highcharts.chart('container', {
chart: {
type: 'line',
//zoomType: 'xy',
//panning: true,
//panKey: 'shift'
},
//chart: {
// renderTo: 'container',
// type: 'line',
// marginRight: 130,
// marginBottom: 25
//},
title: {
text: 'Destination Count Month Wise'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '{y}',
}
}
},
xAxis: {
categories: Xaxis
},
yAxis: {
labels: {
formatter: function () {
return this.value ;
}
},
plotLines: [{
//value: 0,
width: 1,
color: '#808080'
}]
},
series: [{
//name: 'Id',
data: dataseries
}],
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
});
for (var i = 0; i < dataseries.length; i++) {
//dataseries = dataseries.filter(function (e) {
// return e.Month == dataseries[i].Month
//}
//);
chart.addSeries({
name: dataseries[i].destination,
data: [dataseries[i].A1ResultCount]
});
//chart.series[i].setData(dataseries[i].data);
}
//chart.redraw();
}
Rendered Chart
Maybe consider using a web-component that handles dynamic data?
Using highcharts-chart you could do:
const chart = $('#Chart')[0]
function OnSuccess1_(response) {
var Xaxis = [];//skapa tre olika array
var dataseries = [];
for (var i = 0; i < response.d.length; i++) {
var items = response.d[i];
var XcategoreisItem = items.Month;
var seriesData = items;
if ($.inArray(XcategoreisItem, Xaxis) == -1) {
Xaxis.push(XcategoreisItem);
dataseries.push({name: items.month, data: items.data_maybe})
}
chart.data = dataseries
}
}
//Example Data
chart.xAxis = {categories: ['Jan','Feb','Mar','Apr','May','Jun']}
chart.data = [43,81,52,84,53,45]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="import" href="https://user-content-dot-custom-elements.appspot.com/avdaredevil/highcharts-chart/v2.0.1/highcharts-chart/highcharts-chart.html">
<highcharts-chart id='Chart' title='Destination Count Month Wise' type='line' y-label='Destinations' x-label='Month'></highcharts-chart>
Note: Click Run code snippet to see the chart
Edit:
As I was writing this answer, I also realized you were setting categories for a line series? You don't need categories, instead, you need multiple series itself, each with their own name corresponding to the month.

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.

Flash Messages in MVC

I was trying to use flash messages in my MVC project, following these instructions:
http://10consulting.com/2011/08/29/asp-dot-net-mvc-flash-messages-with-razor-view-engine/
https://gist.github.com/13orno/d44d0117f17bcd9d0cb7
I added the package Install-Package FlashMessageExtension by the nuget, and were created some items:
FlashMessageExtensions.cs;
_Flash.cshtml;
jquery.flashmessage.js;
jquery.cookie.js;
And as the instructions said, I added it into my _Layout.cshtml:
<script src="#Url.Content("~/Scripts/jquery.cookie.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.flashmessage.js")"></script>
#Html.Partial("_Flash")
In my controller I'm calling:
using MyProject.Extensions;
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name")] Model model)
{
if (ModelState.IsValid)
{
db.Model.Add(model);
db.SaveChanges();
return RedirectToAction("Index").Success("Create was successful");
}
return View(model);
}
For some reason it isn't working, can someone help me?
ERRORS
SCRIPT5009: 'jQuery' is not defined
jquery.cookie.js, line 60 Character 1
Line: jQuery.cookie = function (key, value, options) {
SCRIPT5009: '$' is not defined
jquery.cookie.js, line 1 Character 1
Line: $.fn.flashMessage = function (options) {
SCRIPT5009: '$' is not defined
Create, line 149 Character 5
Line: $("#flash-messages").flashMessage();
Generated Codes:
jquery.cookie.js
jQuery.cookie = function (key, value, options) {
// key and at least value given, set cookie...
if (arguments.length > 1 && String(value) !== "[object Object]") {
options = jQuery.extend({}, options);
if (value === null || value === undefined) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
value = String(value);
return (document.cookie = [
encodeURIComponent(key), '=',
options.raw ? value : encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// key and possibly options given, get cookie...
options = value || {};
var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
jquery.flashmessage.js
$.fn.flashMessage = function (options) {
var target = this;
options = $.extend({}, options, { timeout: 5000, alert: 'alert-info' });
if (!options.message) {
setFlashMessageFromCookie(options);
}
if (options.message) {
var alertType = options.alert.toString().toLowerCase();
if(alertType === "error") {
alertType = "danger";
}
$(target).addClass('alert-' + alertType);
if (typeof options.message === "string") {
$('p', target).html("<span>" + options.message + "</span>");
} else {
target.empty().append(options.message);
}
} else {
return;
}
if (target.children().length === 0) return;
target.fadeIn().one("click", function () {
$(this).fadeOut();
});
if (options.timeout > 0) {
setTimeout(function () { target.fadeOut(); }, options.timeout);
}
return this;
_Flash.cshtml
<script type="text/javascript">
$(function () {
$("#flash-messages").flashMessage();
});
$(document).ajaxComplete(function () {
$("#flash-messages").flashMessage();
});
</script>
You need to include jQuery as well as the flash message scripts:
<script src="#Url.Content("~/Scripts/jquery.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.cookie.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.flashmessage.js")"></script>
It should have downloaded jQuery with it and make sure jQuery is always loaded before all of the other scripts.

Javascript populate Telerik MVC combobox from an array

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.

Categories