I am quite new to JavaScript and jQuery, although I have often used jQuery UI Components, I barely made any modifications before. In this case, I needed to adjust the jQuery Slider to adjust the date, and I created something as the following: http://jsfiddle.net/ryn_90/Tq7xK/6/.
I'm happy with that so far, and now that I got the slider working as I would like it to, I would like to be able to bind a C# HiddenValue from the JavaScript attribute or from the HTML so I can save the date I have. Unless there is any better method to get this value to the backend...
So far I have been able to bind a JavaScript value from c# variables, but have not found out how to do it the other way round.
This is my javascript code:
<script>
$(function () {
$("#dialog").dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
jQuery(function() {
var dlg = jQuery("#sliderPopup").dialog({
draggable: true,
resizable: true,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
},
width: 320,
autoOpen: false,
minHeight: 10,
minwidth: 10
});
dlg.parent().appendTo(jQuery("form"));
});
$("#popupOpener").click(function () {
$("#dialog").dialog("open");
});
$("#sliderPopupOpener").click(function () {
$("#sliderPopup").dialog("open");
});
});
$(function () {
$("#slider").slider({
max: 30,
min: -30,
value: 0,
slide: function (event, ui) {
$("#days").val(ui.value);
$("#date").text(addDaysToDate(parseInt($("#days").val())));
},
create: function (event, ui) {
$("#date").text(addDaysToDate(parseInt($("#days").val())));
}
});
});
$("#days").val($("#slider").slider("value"));
$("#days").change(function (event) {
var data = $("#days").val();
if (data.length > -30) {
if (parseInt(data) >= 0 && parseInt(data) <= 30) {
$("#slider").slider("option", "value", data);
}
else {
if (parseInt(data) < -30) {
$("#days").val("-30");
$("#slider").slider("option", "value", "-30");
}
if (parseInt(data) > 30) {
$("#days").val("30");
$("#slider").slider("option", "value", "30");
}
}
}
else {
$("#slider").slider("option", "value", "0");
}
$("#date").text(addDaysToDate(parseInt($("#days").val())));
});
function addDaysToDate(days) {
var mths = new Array("Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec");
var d = new Date(<%=deadlineYear%>, <%=deadlineMonth%>, <%=deadlineDay%>);
d.setHours(d.getHours() + (24 * days));
var currD = d.getDate();
var currM = d.getMonth();
var currY = d.getFullYear();
return mths[currM] + " " + currD + ", " + currY;
}
jQuery(function() {
var dlg = jQuery("#sliderPopup").dialog({
draggable: true,
resizable: true,
show: 'Transfer',
hide: 'Transfer',
width: 320,
autoOpen: false,
minHeight: 10,
minwidth: 10
});
dlg.parent().appendTo(jQuery("form"));
});
</script>
This is the asp.NET Code:
<div id="sliderPopup" title="Modify Deadline">
<div id="slider"></div>
<input type="text" id="days" value="0"/>
<div id="date"></div>
<asp:HiddenField ID="ModifiedDeadlineDateFromSlider" />
<asp:Button ID="DeadlineDateSave" Text="Save Deadline" runat="server" OnClick="saveDeadline" />
</div>
Please let me know if you need any more information. I would appreciate your answers and comments.
You can set the date value to the hidden field by adding just single line of code. Add the following code inside the slide event and the create event of your .slider function
$("#ModifiedDeadlineDateFromSlider").val(addDaysToDate(parseInt($("#days").val())));
or
$("#ModifiedDeadlineDateFromSlider").val($("#date").text());
Your .slider function will look like this after the modification.
$(function () {
$("#slider").slider({
max: 30,
min: -30,
value: 0,
slide: function (event, ui) {
$("#days").val(ui.value);
$("#date").text(addDaysToDate(parseInt($("#days").val())));
$("#ModifiedDeadlineDateFromSlider").val($("#date").text());
},
create: function (event, ui) {
$("#date").text(addDaysToDate(parseInt($("#days").val())));
$("#ModifiedDeadlineDateFromSlider").val($("#date").text());
}
});
});
P.S. Add the mentioned line of code to create event only if you want to set date in hidden field value on creation of slider also. If you want to set only if date is changes then just add that code in slide event only.
Note: In this particular scenerio it was not working with the changes also. So after discussion and couple of trials we discovered one more thing which was minor but created the problem. asp hidden field's property ClientIDMode was not set to static due to which its ID was changed during rendering and as a result value was not available in code behind late
Hope that helps!
To pass javascript value to c# do this way:
<script type="text/javascript">
function abc()
{
var str = "yourValue";
document.getElementById("HiddenField1").value = str;
}
</script>
and then access HiddenField1.Value on code-behind.
To pass c# variable to javascript you can bind public variable like this:
<%=this.YourVariable%>
Related
How to get pass id value of button to jquery dialog on button click.
I don't want to pass value using query string.Is there any way that i can directly pass value using attributes or properties of jquery dialog.
View:
<input type="button" value="Create New" class="Create" id="1"/>
Jquery:
$(".Create").on("click", function (e) {
var Id=$(this).atrr('id');
$('#Load').empty();
//overflow: visible !important;
e.preventDefault();
$('#Load').dialog({
autoOpen: true,
modal: true,
draggable: true,
resizable: false,
height: 500,
width: 600,
position: { my: "center", at: "center", of: window },
dialogClass: 'fixed-dialog',
title: 'Create New Word',
open: function (event, ui) {
$(this).load("/Dictionary/_Create");
},
//close: function (event, ui) {
// window.location.href = window.location.href;
//}
});
return false;
});
You can change this line
var Id=$(this).atrr('id'); To BTW atrr is suppose to be attr
CurrentId = $(this).attr('id'); without the var
Then in the page /Dictionary/_Create you can simple access the CurrentId variable using javascript since it's global
I'm developing a web application with Telerik Kendo in Razor. Here is my problem:
I have a variable that I set as a type List<class>.
#{
ViewBag.Title = "Home Page";
var dpdminst = new DB();
var data = dpdminst.getdata();}
I want to be able to use this variable (data) to set my DataSource in my Javascript:
<script>
var displaydata = #data
$(document).ready(function () {
$("#grid").kendoGrid({
height: 550,
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataSource: {
data:displaydata,
schema: {
model: {
fields: {
amount: { type: "string" },
}
}
},
columns:["amount"]
}
});
});
</script>
Does anyone know if this can be done?
Here is my JsonResult:
public JsonResult GetJsonData()
{
var DBinst = new DB();
var TradeData = DBinst.tradedata();
var json = JsonConvert.SerializeObject(TradeData);
var result = new JsonResult()
{
Data = json
};
return result;
}
Have an action method which returns the data you want in JSON format. in your document.ready event, make an ajax call to get this data and then you can set it as your data source.
public ActionResult GetJsonData()
{
var dpdminst = new DB();
var data = dpdminst.getdata();
return Json(data,JsonRequestBehaviour.AllowGet);
}
and in your view use the getJSON method to get data from this action method and use that as needed. You may format the incoming json as per your UI requirements
$(document).ready(function () {
$.getJSON("#Url.Action("GetJsonData","YourControllerName")",function(data){
// you have your json data in the "data" variable.
// now you may use it to set the data source of your grid library
});
});
If you dont want to deal with ajax/json, then I would try to achieve what you want as follows:
<script>
var displaydata = [
#foreach (var record in dpdminst.getdata())
{
#: { amount: '#record' },
}
];
$(document).ready(function () {
$("#grid").kendoGrid({
height: 550,
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataSource: {
data:displaydata,
schema: {
model: {
fields: {
amount: { type: "string" },
}
}
},
},
columns:["amount"]
});
});
</script>
Also please notice that you had columns:["amount"] in a wrong place, also this code has to be in your cshtml for razor syntax to work properly.
How do I plot highchart Gauge with JSON Data?
I am working on highchart gauge, I got succes in showing the latest data from the database. I used JavaScriptSerializer for that
The code is..
<script type="text/javascript">
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'gauge',
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false
},
//Other char parameter comes here
}
function (chart) {
setInterval(function () {
$.getJSON("S14.aspx", function (data, textStatus) {
console.log(data);
$.each(data, function (index, wind) {
var point = chart.series[0].points[0],
newVal = wind;
point.update(newVal);
});
});
}, 3000);
});
The code for JSON is
public string chartData1
{
get;
set;
}
protected void Page_Load(object sender, EventArgs e)
{
List<double> _data = new List<double>();
GetData();
foreach (DataRow row in dt.Rows)
{
_data.Add((double)Convert.ToDouble(row["S11"]));
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData1 = jss.Serialize(_data);
}
My JSON looks like
[1387204961992.4268,72]
Well the problem is that the dial of gauge is not moving according to the last values i need to refresh the page for that. I know this is happening because the GetData function is being executed only one time. I am stuck here.
How do I get the dial move according to the last values updates in the database?
Try to place this part of code
setInterval(function() {
$(function() {
$.getJSON('S12.aspx', function(data) {
$.each(data, function(val) {
if (val !== null)
{
var point = chart.series[0].points[0];
point.update(val);
}
});
});
})
},2000)
Inside callback chart, like here: http://www.highcharts.com/demo/gauge-speedometer
If you receive any errors,please attach.
I think there is a bug or something in the visual studio 2012 . I just paste the entire code on the new aspx page it it got working. I have not done anything else I just pasted the code on another page.
<script type="text/javascript">
$(function () {
$('#container1').highcharts({
chart: {
type: 'gauge',
alignTicks: false,
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false
},
title: {
text: 'Pressure Meter'
},
pane: {
startAngle: -150,
endAngle: 150
},
yAxis: [{
min: 0,
max: 1000,
lineColor: '#339',
tickColor: '#339',
minorTickColor: '#339',
offset: -25,
lineWidth: 2,
labels: {
distance: -20,
rotation: 'auto'
},
tickLength: 5,
minorTickLength: 5,
endOnTick: false
}, {
min: 0,
max: 1000,
tickPosition: 'outside',
lineColor: '#933',
lineWidth: 2,
minorTickPosition: 'outside',
tickColor: '#933',
minorTickColor: '#933',
tickLength: 5,
minorTickLength: 5,
labels: {
distance: 12,
rotation: 'auto'
},
offset: -20,
endOnTick: false
}],
series: [{
name: 'Pressure',
data: [80],
dataLabels: {
formatter: function () {
var psi = this.y,
bar = Math.round(psi / 14.50);
return '<span style="color:#339">' + psi + ' psi</span><br/>' +
'<span style="color:#933">' + bar + ' bar</span>';
},
backgroundColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#DDD'],
[1, '#FFF']
]
}
},
tooltip: {
valueSuffix: ' psi'
}
}]
},
// Add some life
function (chart) {
setInterval(function () {
$.getJSON("S12.aspx", function (data, textStatus) {
$.each(data, function (index, wind) {
var point = chart.series[0].points[0],
newVal = wind;
point.update(newVal);
});
});
}, 3000);
});
});
</script>
In order for the chart to update, the browser somehow needs to request the latest data from the server. There are two ways it can do this:
A page refresh - the whole page is fetched again, with the latest data.
An Ajax request. This makes a request for just the data, without re-loading the entire page.
I presume you would like to update the chart without reloading the entire page. In order do to this, you need to find out about making ajax requests using jquery.
The highcharts site has some resources which will help you (e.g. http://www.highcharts.com/docs/working-with-data/preprocessing-live-data). You need to learn how to make an ajax call in javascript, and use the returned data to update your chart. You will also need to write the server side part which returns the ajax data. The example given is in php, but it should be fairly straight forward to do something similar in asp.net.
I just recently started in Asp.Net MVC and I am just clueless at the moment. So my task is to localise text in .js files. My problem is that I can't seem to display this dialog label in my browser, the text I want to replace is "Remove A to B". I have tried using my variable 'a' by going 'this.a' in the place of this text but it doesn't work.
function Remove() {
var a = "";
this.Load = function () {
...`enter code here`
});
this.InitEventHandlers = function () {
$("#updateRemove").click(function (e) {
amplify.publish("UpdateRemove");
e.preventDefault();
});
$("#removeA").click(function () {
$("#removeA").dialog({
title: "Remove A to B",
width: 300,
autoOpen: true,
modal: true,
draggable: false,
resizable: false,
dialogClass: "RemoveB",
open: function () { $(this).appendTo("RemoveC"); }
});
});
...
you need to store the reference of 'this' because in the object inside the remove function the context is the current object.
do this:
function Remove() {
var that = this;
that.a = "";
$("#removeA").click(function () {
$("#removeA").dialog({
title: that.a,
you can read a little bit more here: http://javascript.crockford.com/private.html
Currently I have this auto complete option:
<script type="text/javascript">
$().ready(function () {
$("#tags").autocomplete(["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby", "python", "c", "scala", "groovy", "haskell", "pearl"], {
width: 320,
max: 4,
highlight: false,
multiple: true,
multipleSeparator: " ",
scroll: true,
scrollHeight: 300
});
});
</script>
<body> <p>
<label>Tags (local):</label>
<input type="text" id='tags' />
</p>
</body>
But I would like to get this array from an action method: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby", "python", "c", "scala", "groovy", "haskell", "pearl"]. For example from action "QuickSearch" in controller "Search".
So something like this:
public ActionResult QuickSearch(string term)
{
IEnumerable<string> list = test();
return Json(list, JsonRequestBehavior.AllowGet);
}
Any suggestions?
Yes, you can put the URL to the action method that returns the datasource as the "source" parameter to the autocomplete function. From the documentation:
A data source can be:
an Array with local data
a String,specifying a URL
a Callback
You almost have it there:
<script type="text/javascript">
$().ready(function () {
$("#tags").autocomplete({
source: "URL to your method"
width: 320,
max: 4,
highlight: false,
multiple: true,
multipleSeparator: " ",
scroll: true,
scrollHeight: 300
});
});
</script>
You need to add a source property to the options object that is passed in, and that source can be an array, a callback, or in your case a URL to a method.
Where the relative URL from the root would be "Search/QuickSearch"