I am using following code and it always picks up hard coded data defined in availableTags. If I dynamically load data from C# WebApi, it still picks up old data i.e. ActionScript and AppleScript.
As you can see I am printing Before and After values and they both are working correctly i.e. as I can see it assigns new data to availableTags but autocomplete still works on old data. Is there a limit on how many items can I define in availableTags? Because dynamically it is getting 504 items from my code so may be this is the issue?
What am I doing wrong?
<input id="tags">
<script>
var availableTags =
[
"ActionScript",
"AppleScript"
];
$("#tags").autocomplete
({
source: availableTags
});
$.getJSON("MyController/GetAllTags")
.done(function (data)
{
alert("Before="+ availableTags);
availableTags = data;
alert("After="+ availableTags);
});
</script>
Try this
<input id="tags">
<script>
var availableTags =
[
"ActionScript",
"AppleScript"
];
$("#tags").autocomplete
({
source: availableTags
});
$.getJSON("MyController/GetAllTags")
.done(function (data)
{
$("#tag").autocomplete('option', 'source', data)
});
</script>
Edit 1: Updating Code
Related
I am implementing a simple JQuery autocomplete with few entries so I don't need to use a web method. The code is like this:
$( function() {
var availableTags = [
"ActionScript",
"AppleScript"
];
$( "#tags" ).autocomplete({
source: availableTags
});
} );
The entries availableTags are unique to the user so they need to come from the server. How should I get the entries from the server side to the JavaScript in ASP.NET Core?
This assumes you have some service IUserTagService like this, registered through dependency injection:
public interface IUserTagService
{
IList<string> GetUserTags();
}
Since you don’t want (or need) an AJAX call here to load the tags after the page has been rendered, we’re just going to render the tags directly into the output. For that, we basically convert the returned list from the GetUserTags method into JSON and put this into a script tag. So the end result will look mostly like your static example.
So in the .cshtml view, we first inject our service. We can use the #inject directive at the beginning of the file for this:
#inject IUserTagService userTagService;
Then, we simply open a script tag and write the output into a variable:
<script>
$(function() {
var availableTags = #Json.Serialize(userTagService.GetUserTags());
$("#tags").autocomplete({
source: availableTags
});
});
</script>
This uses the Json.Serialize which is a utility function that is available in views to serialize the list into JSON.
You can make an ajax call to your server action method which returns the list as JSON array.
$(function () {
$.getJSON("#Url.Action("GetItems")", function (availableTags) {
$( "#tags" ).autocomplete({
source: availableTags
});
});
})
Assuming your GetItems action method returns the list of items as json array
public JsonResult GetItems()
{
var list = new List<string>() {"ActionScript","AppleScript"};
return new JsonResult(list);
}
Another option is to load the data (list of strings to your main views GET action method and in the razor view, convert that to a JS Array
So in your GET action,
var list = new List<string>() {"ActionScript","AppleScript"};
ViewBag.Items = list;
return View();
and in the razor view,
#section Scripts
{
<script>
$(function() {
var availableTags = #Html.Raw(Newtonsoft.Json.JsonConvert
.SerializeObject(ViewBag.Items));
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
}
Dependency injection is possible in asp.net core views now. poke's answer above uses that. You may consider doing that instead of the ViewBag solution above.
below is my json generated data from the backend
{"langs":[{"cisAreaId":100,"area":"Prog","name":"C#"},{"cisAreaId":110,"area":"Prog","name":"Java"},{"cisAreaId":120,"area":"Prog","name":"MS.NET languages(VB.NET,etc)"},{"cisAreaId":130,"area":"Prog","name":"MS Visual Languages (VB, C++, etc)"},{"cisAreaId":140,"area":"Prog","name":"Python"},{"cisAreaId":150,"area":"Prog","name":"Ruby"}]}
above data i copied to $scope.areas.
Now in my view
<div ng-repeat="lang in areas.langs">
<label><input type="checkbox" ng-model="lang.selected" value="{{lang.cisAreaId}}" /> {{lang.name}}</label>
</div>
once user click the submit, I need to capture selected checkbox values and send it as JSON data.
$scope.languageArray = [];
angular.forEach($scope.areas.langs, function (lang) {
if (lang.selected) $scope.languageArray.push({ "cisAreaId": lang.cisAreaId });
});
var data = JSON.stringify({
languages: $scope.languageArray,
});
it is forming the array like after selecting the two of the checkbox values
{"languages":[{"cisAreaId":110},{"cisAreaId":120}]}
From the above code how can I pass the above dynamic array in the URL to call the backend method
Angularjs Controller Code:
XXXService.step2Form(data).then(function (results) {
console.log(results.data);
}, function (error) {
alert(error.data.message);
});
service code:
var _step2Form = function (data) {
return $http.post(serviceBase + 'api/feedback/Step2Data' + data , { headers: { 'Content-Type': 'application/json' } });
};
I have pass the data dynamically to the backend
public HttpResponseMessage Step2Data([FromBody] int[] languages)
but i am getting the error like this
http://localhost:53401/api/XXXX/Step2Data[object%20Object],[object%20Object] 404 (Not Found)
can anyone please tell me how to pass the array values dynamically in the url to call the webapi method.
in $scope.languageArray you need to push just the id :
$scope.languageArray = [];
angular.forEach($scope.areas.langs, function (lang) {
if (lang.selected) $scope.languageArray.push(lang.cisAreaId);
});
var data = JSON.stringify({
languages: $scope.languageArray,
});
I am using a JS method to assign the names of computer languages to data attribute of div
e.g
<div id="Languages" data-Languages=''></div>
and js code
var langs='["Perl", "PHP", "Python", "Ruby", "Scala", "C#"]';
$('#Languages').data('Languages', langs);
but when i type text in the textbox it gives me an error
Object Expected
i am using this line for autocomplete
$(function () {
$("#tags").autocomplete({ source: $('#Languages').data('Languages') });
});
it works totally fine when i make another variable and pass it as a source as implemented in jquery website
i want to handle it with div's data attribute because in future i want to use JSON that fetches autocomplete data on page load and assign it to div data attribute.
sorry if that question sounds stupid, its my 2nd day with jquery and all that stuff.
Not sure if this is your problem exactly but you have single quotes around your array, making it a string.
it should be:
var langs = ["Perl", "PHP", "Python", "Ruby", "Scala", "C#"];
your langs is like '' which makes it a string. you need an array which behaves like a source for autocomplete. Also there is a mismatch in id and key of data you are trying. try this
var langs = ["Perl", "PHP", "Python", "Ruby", "Scala", "C#"];
$('#locations').data('languages', langs);
$(function () { $("#tags").autocomplete({
source: $('#locations').data('languages') });
});
problem is you are assigning data to div outside page ready function, when div is not actually been loaded on page. try below mentions code, it works fine for me.
$(function () {
var langs = ["Perl", "PHP", "Python", "Ruby", "Scala", "C#"];
$('#locations').data('languages', langs);
$("#tags").autocomplete({
source: $('#locations').data('languages') });
});
This is not much different from #Rahul solution.
but maybe you want to read directly from the data attribute:
var langs = ["Perl", "PHP", "Python", "Ruby", "Scala", "C#"];
$('#locations').attr('data-Languages', langs);
$(function () { $("#tags").autocomplete({
source: $('#locations').data('languages').split(',')});
});
working example: http://jsbin.com/oyusub/4/
I am using asp.net mvc2.I have a listbox and textbox when i select an item from listbox corresponding value to that item should appear in textbox from database.please help
You should use JavaScript for handle listbox selection changes.
And read about Ajax, it neads to get the data from DB without reloadin page.
Add
Example how can you handle listbox selection changes.
#Html.ListBox("nam",new SelectList(new string[]{"opt1","opt2"}),new {onchange = "javaScript:actch()", id = "namid"})
<script type="text/javascript">
function actch() {
alert(document.getElementById("namid").value);
}
</script>
Value "document.getElementById("namid").value" contains option that you select.
You should send this value to the server and recieve request
#Html.ListBox("nam",new SelectList(new string[]{"opt1","opt2"}),new {onchange = "javaScript:actch()", id = "namid"})
<script type="text/javascript">
function actch() {
$.ajax({
url: "your url",
type: "POST",
data: "id = " + document.getElementById("namid").value,
success: function (data) {
// action on success
document.getElementById("TextBoxId").value = data;
},
error: function (jqXhr, textStatus, errorThrown) {
// action on fail
},
complete: function () {
}
});
}
</script>
You have to write a server request part, and configure ajax.
(I had use jQuery)
Added: Server request part (example)
[HttpPost]
public MvcHtmlString Detail(string id)
{
var d = _db.GetVehicle(Convert.ToInt32(id));
var sb = new StringBuilder();
sb.AppendLine(string.Format("Type: {0}</br>", d.Type));
sb.AppendLine(string.Format("Brand: {0}</br>", d.Brand));
sb.AppendLine(string.Format("Model: {0}</br>", d.Model));
sb.AppendLine(string.Format("Number: {0}</br>", d.Number));
sb.AppendLine(string.Format("Year: {0}</br>", d.Year));
sb.AppendLine(string.Format("Cost: {0}</br>", d.Cost));
return new MvcHtmlString(sb.ToString());
}
URL looks like: MyController/Detail/
DATA for ajax: "id=" + document.getElementById("namid").value
P.S. Some one edit/spoil my ansver and it's not marked(
Your question is a little vague but this is basically how it can be done:
You can post the value of the listbox in the change event by using jquery (or any other JS library of your preference). Then the controller gives a value back, which you then put in the textbox.
Check out http://api.jquery.com/jQuery.post/
In my aspx page, i have the js like this :-
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = "{'datakey':'hello'}"
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});
</script>
In the same webpage code behind class file ,i have the webmethod defined like this:-
[WebMethod]
public static string SendFile(string key, string data)
{
return data;
}
For some reason, i am able to get the data in the alert used on the html side. alert(msg); is giving me nothing and i am expecting to get the passed value back. In this case it should be 'Hello'.
I am missing something very small here, please help me out here.
Alter these.
The AJAX Call
$(document).ready(function () {
$("#btnLoad").click(function (evt) {
var dataForAjax = "{'datakey':'hello'}";
$.ajax({
contentType: "application/json",
data: dataForAjax,
type: "POST",
url: 'Test1.aspx/SendFile',
success: function (msg) {
var msg = msg.hasOwnProperty("d") ? msg.d : msg;
alert(msg.datakey);
}
});
evt.preventDefault();
});
});
The WebMethod
[WebMethod]
public static object SendFile(string datakey)
{
return new
{
datakey = datakey
};
}
Hope this helps.
Update:
`evt.preventDefault is for preventing postback in case your control was something like input type="submit" or asp:Button
.d is ASP.NET 3.5+ feature to prevent XSS vulnerability. ( link here )
The return type is object for the web method for automatic serialization ( link here )
Also you could omitdataType in $.ajax call but contentType is an absolute necessity ( link here )
This:
var dataForAjax = "{'datakey':'hello'}"
Should be:
var dataForAjax = {'datakey':'hello'}
AJAX does not (by default anyway) send json - it sends FORM INPUT elements! jQuery is nice and will convert javascript objects into that for you.
If you really need to you can send json, but I really doubt you do, it's rare to do that.
When you send data to method you must send apropriate key-value pairs, using object in Javascript.
Examle for you method:
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = {'key' :'datakey', 'data' : 'hello'};
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});