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"
Related
How can I call action method from jquery ajax form? I create below code, but parameters in my action method is always null.
Note: I already added all needed scripts, such as quill.js, jquery.unobtrusive-ajax.js
I have this form:
<form data-ajax="true" data-ajax-method="post" method="post">
<input type="text" name="postTitle" class="form-group" />
<div id="postData" name="postData"></div>
<br />
<button type="submit" class="btn btn btn-outline-dark" id="btnCreate">Create post</button>
</form>
and this javascript and jquery scripts:
QUILL:
<script>
var toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
['link', 'image', 'video', 'formula'], // add's image support
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'font': [] }],
[{ 'align': [] }],
['clean'] // remove formatting button
];
var quill = new Quill('#postData', {
modules: {
toolbar: toolbarOptions
},
theme: 'snow'
});
</script>
Calling post action method:
$(function () {
$('#btnCreate').click(function () {
var props = [{
"PostTitle": $("postTitle"),
"PostData": quill.root.innerHTML
}]
$.ajax({
url: '#Url.Action("Create", "Post")',
type: "POST",
data: { JSON.stringify(props) },
contentType: "application/json",
dataType: "json",
async: true,
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc(e) {
console.log('Error!', e);
}
//console.log(postData);
});
});
My action method:
[HttpPost]
[ActionName("Create")]
public async Task<IActionResult> CreatePost(string props) // here props is null
{
Post post = new Post { PostBody = props };
db.Posts.Add(post);
await db.SaveChangesAsync();
return View();
}
I think that every input element is obtained from val ();
$("postTitle").val() maybe
I'm trying to feed a Highchart chart with data using a viewmodel but can't get it to work.
The list of strings I want to use in my chart is populated in the model like this:
var list = new List<ClinicPatients>();
foreach (var customer in customers)
{
var customerName = GetCustomerName(customer);
var numOfPatients = GetNumOfActivePatients(customer);
list.Add(new ClinicPatients { ClinicName = customerName, PatientNumber = nummOfPatients });
}
public string ClinicList { get; set; }
var tempList = list.Select(x => x.ClinicName);
ClinicList = JsonConvert.SerializeObject(tempList);
When i debug this and choose to text visualizer i see this in ClinicList:
["A","B","C","D","E","F"] which looks right. If I copy this and hard code it to my javascrip it works but when my javascrip is bound to my viewmodel i does not work. Could someone please explain why?
Model.ClinicUsers which is a list of int works as well.
My Html/Javascript looks like this:
<div class="content">
<div>
<div id="usersPerClinicDiagram" style="width: 800px; height: 300px;">
<div id="activUsers" style="width: 800px; height: 300px;"></div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
var usersPerClinicDiagram = new Highcharts.Chart({
chart: {
renderTo: 'activUsers',
type: 'bar'
},
legend: {enabled: false},
title: {text: 'Number of active users per clinic'},
subtitle: {text: 'for how many weeks they kept on using Triabetes'},
tooltip: {enabled: false},
xAxis: {
title: {text: 'number of users',align: 'high'},
allowDecimals: false,
categories: #Model.ClinicList
},
yAxis: {min: 0,
allowDecimals: false,
title: {text: 'Clinic',align: 'high'},
labels: {overflow: 'justify'}
},
plotOptions: {
bar: {dataLabels: {enabled: false}
}
},
credits: {enabled: false},
series: [{ data: #Model.ClinicUsers }]
});
});
});
</script>
Try this:
#Html.Raw(Json.Encode(Model.ClinicUsers.ToArray()))
Worked for me.
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 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%>
I was trying to customize google Column chart to add my own data from controller.
I found easy solution but if someone knows better approach I am happy to modify my code.
Assuming that we copy the code from https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="width:50%;float:left"></div>
So the first think I wanted to amend was to display Category name and number of orders.
Solution was simple, I just removed Expensed so it looked like this:
['Category', 'Orders'],
['2004', 1000,],
['2005', 1170, ],
['2006', 660, ],
['2007', 1030, ]
But those are hard coded data and I wanted to have my own category names and name of orders from my Data base.
I created in controller custom string and then pass it to script.
Controller:
foreach (var d in model.DinerCategoryOrders) // Build string for google chart js
{
// ['Pre-School', 1000], Template
GoogleOrdersCount += "['" + d.CategoryName + "', " + d.OrdersCount + "],";
}
model.OrdersForGoogleChart = "google.visualization.arrayToDataTable([['Category', 'Orders']," + GoogleOrdersCount +" ]);";
return model;
In View
I replaced data variable definition simply with my string that I built in controller:
#Html.Raw(Model.OrdersForGoogleChart)
so final build looks like that:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = #Html.Raw(Model.OrdersForGoogleChart)
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I found amazing that Razor in Asp.Net MVC speaks with js and js will digest string that was passed through razor without any issues.
If you find a beter solution to I believe common problem let us know!