I have a js code in which an array works well when its like
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C"
];
I then made an array string in my code behind or .cs like on class level
public static string[] test={"animal","lovely"};
I then changed js array to this
var availableTags = "<%=test%>"; // also tried without quotes
Now I m not having the results as was having with previous js array
Editing with complete code,the jquery I taken from http://jqueryui.com/demos/autocomplete/#multiple
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Web.Script.Serialization;
public partial class onecol : System.Web.UI.Page
{
JavaScriptSerializer serializer;
public static string test = "['animal','lovely']";
public static string check;
protected void Page_Load(object sender, EventArgs e)
{
serializer = new JavaScriptSerializer();
//serializer
this.detail.ToolsFile = "BasicTools.xml";
test = returnTitle();
}
}
and the script with html is
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript" src="Jscript.js"></script>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.17.custom.css"></script>
<link href="~/jquery-ui-1.8.17.custom.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(function () {
var availableTags = <%=test%>;
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#tags")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function (request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="demo" >
<div class="ui-widget">
<label for="tags">Tag programming languages: </label>
<input id="Text1" class="#tags" size="50" />
</div>
</div>
actually its a auto complete functionality to give tags ,the auto complete suggestions for tagging I want to get from C# code ,I took Jquery source from jqueryui.com/demos/autocomplete/#multiple and then I tried to give it C# string from .cs file , I explained it with code on edited version , with C# code behind it works exactly as its in the link
You need to serialize the C# string array into a javascript array.
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
Usually I create a simple static class as a wrapper.
public static class JavaScript
{
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
}
Then you can use that class to serialize the item you need to
//C# Array(Member of asp page)
protected string[] Values = { "Sweet", "Awesome", "Cool" };
<script type="text/javascript">
var testArray = <%=JavaScript.Serialize(this.Values) %>
</script>
var availableTags = ['<%=String.join("','",test)%>'];
It would be something like this...
var availableTags = ["<%= string.Join("\", \"", test) %>"];
or
var availableTags = ['<%= string.Join("', '", test) %>'];
The first one would render as
var availableTags = ["Sweet", "Awesome", "Cool"];
and the second one would render as
var availableTags = ['Sweet', 'Awesome', 'Cool'];
both of which are fine for autocomplete.
test property should be a string property and it should render the string which will be parsed by Js engine as an array. Try this.
Code behind property
public static string test= "['animal','usman lovely']";
JS
var availableTags = <%=test%>;//No quotes
only use indexes to get your test string array
i have tried by giving indexes like
var availableTags = "<%=test[0]%>"; // animal
var availableTags = "<%=test[1]%>"; // lovely
If you're doing an online coding challenge, the browser-based IDE might not let you use string.join, like with my job, which has us use iMocha.
Instead of that, I just created a StringBuilder object (from System.Text) and iterated over the array, appending each integer and a blank space, then converting the result to a string. Something like this:
var array = new int[] {1, 3, 5, 7, 9};
var str = new StringBuilder();
foreach (int i in array)
{
str.Append(i);
str.Append(" ");
}
var result = str.ToString();
Related
I am using GeckoFX16 and xulrunner-16.0.2.en-US.win32 in my project.
The thing is, I want to call a C# method in javascript.
I am curious, is there a way to do this?
Just like below:
C# part:
private GeckoWebBrowser weBrowser;
public browser()
{
InitializeComponent();
Gecko.Xpcom.Initialize("xulrunner");
weBrowser = new GeckoWebBrowser();
weBrowser.Parent = this;
weBrowser.Dock = DockStyle.Fill;
weBrowser.Navigate("test.html");
}
public string loadData(){
//load data from local file.
return str;
}
javascript part:
<script type='text/javascript'>
var data = window.loadData();
alert(data);
</script>
I am new in this area, I’ll appreciate if it is possible!
Important update:
Currently code with event.initMessageEvent does not work because this construction has been replaced on
var event = new MessageEvent('yourEventName', { 'view': window, 'bubbles': false, 'cancelable': false, 'data': 'some data' });
You can use a MessageEvent to invoke code in c#, but as far as I know you can't then return a string like you're wanting to. One of the unit tests demonstrates how to invoke the c# code:
[Test]
public void AddEventListener_JScriptFiresEvent_ListenerIsCalledWithMessage()
{
string payload = null;
browser.AddMessageEventListener("callMe", ((string p) => payload = p));
browser.LoadHtml(
#"<!DOCTYPE html>
<html><head>
<script type='text/javascript'>
window.onload= function() {
event = document.createEvent('MessageEvent');
var origin = window.location.protocol + '//' + window.location.host;
event.initMessageEvent ('callMe', true, true, 'some data', origin, 1234, window, null);
document.dispatchEvent (event);
}
</script>
</head><body></body></html>");
browser.NavigateFinishedNotifier.BlockUntilNavigationFinished();
Assert.AreEqual("some data", payload);
}
I know it's awkward, but you could then use a c#-->javascript call to get data back to javascript-land. See This Question for how to do that. So your javascript would first send this message to c# land, then it would get a callback with the string value you need.
Hope that helps.
You can add message event listener to your web browser and call your method like this:
private void load()
{
browser.AddMessageEventListener("myFunction", ((string s) => this.showMessage(s)));
browser.LoadHtml
(
#"<!DOCTYPE html>
<html><head>
<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"">
<script type=""text/javascript"">
function fireEvent(name, data)
{
event = document.createEvent('MessageEvent');
event.initMessageEvent(name, false, false, data, null, null, null, null);
document.dispatchEvent(event);
}
</script>
</head>
<body>
<input type=""button"" onclick=""fireEvent('myFunction', 'some data');"" value=""SHOW DATA"" />
</body></html>"
);
}
...
private void showMessage(string s)
{
MessageBox.Show(s);
}
Now you can add more msg events to your msg listener (if you need to) and fire them all in the same way.
Does anyone know how, or have any links on how to filter the data returned in a textbox that is based on the value of the selected item in a dropdownlist.
i.e If a user selects hotel from a list, then when they start typing in the textbox only the address of the companies whos category matches hotel will appear using autocomplete.
I have added my server side code below, but I'm getting the following error.
public JsonResult FilterDirectorySearch(string searchText, string context)
{
var wq = DirectoryList(searchText,context).Select(a =>
new { Location = a.strLocationSearch });
return Json(wq.Distinct(), JsonRequestBehavior.AllowGet);
}
private List<DisplayDirectoryDataForSearchBox> DirectoryList(string searchString, string context)
{
var wq = _IGTDD.DisplayDirectoryData()
.Where(a => a.strLocationSearch.Contains(searchString, StringComparison.OrdinalIgnoreCase) && a.strCategory = context).ToList();
return wq.ToList();
}
Errors
Error 1 Instance argument: cannot convert from 'string' to 'System.Linq.IQueryable'
Error 2 'string' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.Queryable.Contains(System.Linq.IQueryable, TSource, System.Collections.Generic.IEqualityComparer)' has some invalid arguments
Error 3 Argument 3: cannot convert from 'System.StringComparison' to 'System.Collections.Generic.IEqualityComparer'
Forgot to add this error for the code below
return (from x in wq where x.strLocationSearch.StartsWith(searchString, StringComparison.OrdinalIgnoreCase) && x.strCategory = context select x.strLocationSearch).AsEnumerable();
Error message: Error 1 Operator '&&' cannot be applied to operands of type 'bool' and 'string'
Any Autocomplete javascript tooling generally allows you to configure the source as a function, being either a javascript function and local data, or a function to an AJAX server source.
Within either the local javascript function or the remove AJAX responder, you can simply add the extra context data, by pulling the value from the required dropdown box.
Handling would then be either in the local javascript code or in the remote AJAX responder to deal with the extra information.
Without any context of what autocomplete coding you are using, it's difficult to illustrate my answer with code.
However, if you're using jQuery, Autocomplete UI and an AJAX function for the source:
$("#autocompleteTextBox").autocomplete({
source: function(request, response) {
var autocompleteContext = $("#dropdownBox").val();
$.ajax({
url: "http://source.com/searchJSON",
dataType: "jsonp",
data: {
query: request.term,
context: autocompleteContext
},
success: function(data) {
...
Note the two lines:
Where autocompleteContext variable is set, presumably from the dropbox you speak of
Where autocompleteContext is fed through to the searchJSON action in the data parameter
On the server-side (handler of searcjJSON) [C#/MVC psuedocode]:
public List<string> searchJSON(string query, string context)
{
return (from x in db.SearchTable where x.Name.Contains(query) && x.context == context select x.Name).ToList()
}
If you're merely using a local array source in javascript, change to a function source, similar to the AJAX source...
var fullArray = ["Apple", "Bat", "Cat", "Dog"];
$("#autocompleteTextBox").autocomplete({
source: function(request, response) {
var autocompleteContext = $("#dropdownBox").val();
response = //Code to filter fullArray with request.term and autocompleteContext here
}
This is fully functional client only example:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css" />
<script type="text/javascript">
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun /*, thisp */) {
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
$(function () {
var availableAddresses = [
"New York Hotel",
"London Restaurant",
"London Hotel",
"Paris Restaurant",
"Berlin Restaurant",
"Moscow Restaurant"
];
$("#businesses").keyup(function () {
$("#businesses").autocomplete({
source: availableAddresses.filter(function (element, index, array) {
return (element.toLowerCase()
.indexOf($("#filter").val().toLowerCase()) !== -1);
})
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select id="filter">
<option>hotel</option>
<option>restaurant</option>
</select>
<input type="text" id="businesses"/>
</div>
</form>
</body>
</html>
I'm using this following code for auto complete feature ,
but I need to fetch values from database using sql server 2008 and C# , asp.net.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</body>
</html>
How can i fetch that array list values from my database using (EF4 and asp.net)
The first step is to create a C# ASP.Net page which produces a JSON result that the autocomplete plugin can parse. According to the documentation you can use the two following formats:
Array: An array can be used for local data.
There are two supported formats: An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value:
"value1" }, ... ]
http://api.jqueryui.com/autocomplete/#option-source
Alternatively you can use a function to parse out whatever format you need but it sounds like the simplest solution will fulfill your needs.
I'm going to assume you're using ASP.Net forms which isn't really tuned for this kind of thing but you can still make it work with some tweaking. Let's create a page in your web application root called SearchResults.aspx.
The first thing to do is to clear out everything from your ASPX file except the line:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SearchResults.aspx.cs" Inherits="ASP.Net_Forms.SearchResults" %>
Then you're free to change the code behind to output whatever format you like. In this case we'll be using JSON in a structure that Autocomplete can understand natively. We'll also need to set the response type.
public partial class SearchResults : System.Web.UI.Page
{
private class SomeSearchableClass
{
public int ID { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
// The autocomplete plugin defaults to using the querystring
// parameter "term". This can be confirmed by stepping through
// the following line of code and viewing the raw querystring.
List<SomeSearchableClass> Results = SomeSearchSource(Request.QueryString["term"]);
Response.ContentType = "application/json;charset=UTF-8";
// Now we need to project our results in a structure that
// the plugin can understand.
var output = (from r in Results
select new { label = r.Name, value = r.ID }).ToList();
// Then we need to convert it to a JSON string
JavaScriptSerializer Serializer = new JavaScriptSerializer();
string JSON = Serializer.Serialize(output);
// And finally write the result to the client.
Response.Write(JSON);
}
List<SomeSearchableClass> SomeSearchSource(string searchParameter)
{
// This is where you'd put your EF code to gather your search
// results. I'm just hard coding these examples as a demonstration.
List<SomeSearchableClass> ret = new List<SomeSearchableClass>();
ret.Add(new SomeSearchableClass() { ID = 1, Name = "Watership Down" });
ret.Add(new SomeSearchableClass() { ID = 2, Name = "Animal Farm" });
ret.Add(new SomeSearchableClass() { ID = 3, Name = "The Plague Dogs" });
ret = ret.Where(x => x.Name.Contains(searchParameter)).ToList();
return ret;
}
}
And finally just change your jQuery to use the correct source:
$( "#tags" ).autocomplete({ source: "/SearchResults.aspx" });
See this below sample from jQueryUI Autocomplete Example
Hope you can do by yourself!.
All you need to do is call some page or handler and prepare JSON data.
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "yourpage.aspx",
dataType: "jsonp",
data: {
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
I have a problem with the events in my fullCalendar object not showing when using ajax to fetch the data from my JSON feed. I believe the JSON format is proper though since the output from JSON.aspx is:
[{"id":1,"title":"TESTTITLE","info":"INFOINFOINFO","start":"2012-08-20T12:00:00","end":"2012-08-20T12:00:00","user":1}]
I used Firebug and it seems like the JSON feed is not getting fetched properly?
When I add the upper JSON-feed directly in the events it displays properly.
(Edit) The JSON response is now working, although the events are still not displayed in fullcalendar.
JSON.aspx
public partial class JSON : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Get events from db and add to list.
DataClassesDataContext db = new DataClassesDataContext();
List<calevent> eventList = db.calevents.ToList();
// Select events and return datetime as sortable XML Schema style.
var events = from ev in eventList
select new
{
id = ev.event_id,
title = ev.title,
info = ev.description,
start = ev.event_start.ToString("s"),
end = ev.event_end.ToString("s"),
user = ev.user_id
};
// Serialize to JSON string.
JavaScriptSerializer jss = new JavaScriptSerializer();
String json = jss.Serialize(events);
Response.Write(json);
Response.End();
}
}
And my Site.master
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href='fullcalendar/fullcalendar.css' rel='stylesheet' type='text/css' />
<script src='jquery/jquery-1.7.1.min.js' type='text/javascript'></script>
<script src='fullcalendar/fullcalendar.js' type='text/javascript' ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#fullcal').fullCalendar({
eventClick: function() {
alert('a day has been clicked!');
},
events: 'JSON.aspx'
})
});
</script>
I've been scanning related questions for days but none of them seems to fix mine...
Why are your calls so complicated? Try this for now:
$('#fullcal').fullCalendar({
events: 'JSON.aspx',
eventClick: function (calEvent, jsEvent, view) {
alert('a day has been clicked!');
}
});
I have implemented an autocomplete in my app for zip codes. I am debugging in Firebug and I see in my console that the action is performing and I get a list of zip codes in the list of results, but the actual list is not displaying when I debug.
Here's the action in my Customers controller:
//the autocomplete request sends a parameter 'term' that contains the filter
public ActionResult FindZipCode(string term)
{
string[] zipCodes = customerRepository.FindFilteredZipCodes(term);
//return raw text, one result on each line
return Content(string.Join("\n", zipCodes));
}
Here's the markup (abbreviated)
<% using (Html.BeginForm("Create", "Customers")) {%>
<input type="text" value="" name="ZipCodeID" id="ZipCodeID" />
<% } %>
and here's the order I load my scripts:
<script type="text/javascript" src="/Scripts/jquery-1.4.2.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.core.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.position.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete({ source: '<%= Url.Action("FindZipCode", "Customers") %>'});
});
</script>
Anything obvious that I'm missing? Like I say the script is grabbing the list of zip codes, they just won't display on my page when I test.
EDIT: I added an image that shows what I see in firebug - it appears that I get my zip codes back, but just won't display the dropdown.
I also updated my text box so that it's inside of the ui-widget div like so:
<div class="ui-widget">
<input type="text" name="ZipCodeID" id="ZipCodeID" />
</div>
and this is the script that I'm using:
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete('<%= Url.Action("FindZipCode", "Customers") %>');
});
</script>
I was able to get the autocomplete suggestions working using the following code:
Controller:
public JsonResult FindZipCode(string term)
{
VetClinicDataContext db = new VetClinicDataContext();
var zipCodes = from c in db.ZipCodes
where c.ZipCodeNum.ToString().StartsWith(term)
select new { value = c.ZipCodeID, label = c.ZipCodeNum};
return this.Json(zipCodes, JsonRequestBehavior.AllowGet);
}
Markup:
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete({
source: '<%= Url.Action("FindZipCode", "Customers") %>',
});
});
</script>
<div class="ui-widget"><input type="text" name="ZipCodeID" id="ZipCodeID" /></div>
I had huge problems with autocomplete few months ago when first setting it up. For instance, the simple default wireup like you do it never worked for me. I had to specify everything and also attach the result function to it.
This works 100% but it might not be suitable for you. But I hope it helps. Put both in document.ready() function.
$("#products").autocomplete('<%:Url.Action("GetProducts", "Product") %>', {
dataType: 'json',
parse: function (data) {
var rows = new Array(data.length), j;
for (j = 0; j < data.length; j++) {
rows[j] = { data: data[j], value: data[j].Title, result: data[j].Title };
}
return rows;
},
formatItem: function (row, y, n) {
return row.PrettyId + ' - ' + row.Title + ' (' + row.Price + ' €)';
},
width: 820,
minChars: 0,
max: 0,
delay: 50,
cacheLength: 10,
selectFirst: true,
selectOnly: true,
mustMatch: true,
resultsClass: "autocompleteResults"
});
$("#products").result(function (event, data, formatted) {
if (data) {
var item = $("#item_" + data.PrettyId),
edititem = $("#edititem_" + data.PrettyId),
currentQuantity;
// etc...
}
});
Try returning JSON from your controller action:
public ActionResult FindZipCode(string term)
{
string[] zipCodes = customerRepository.FindFilteredZipCodes(term);
return Json(new { suggestions = zipCodes }, JsonRequestBehavior.AllowGet);
}
Also don't forget to include the default CSS or you might not see the suggestions div appear.