I want a dropdown menu that allows user to type in text..something like autocomplete with dropdown.
I have been trying this for a long time now and while going through other posts I found people suggesting Ajax but I could not use it.
What are the other options available ?
also,I have to bind the dropdown to a database query so the option must allow that.Thanks a ton!
you can try one of these two :
Chosen
Select2
Try using this code:
$("#DropDOwnID").select2({
ajax: {
url: "https://graph.facebook.com/v2.2/search", //method which returns the data for select2 OR in web forms use web service
type: 'GET',
multiple: true, //if dropdown can have multiple or not
dataType: 'json',
delay: 250,
data: function (params) {
return {
parametername: params.term, // search
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
var myResults = [];
$.each(data.data, function (index, item) {
myResults.push({
'id': item.key,
'text': item.name
});
});
return {
results: myResults
};
},
cache: true
},
minimumInputLength: 1,
});
You can try Select2 https://select2.github.io/
It has Ajax \ plain HTML mode, as well as ability to create pagination for large quantity of items.
You can create it using plain select as data source or even hidden input for ajax \ pagination
Related
I'm working on a application which should return multiple list based on selected values.
When a organisation is selected a few queries will run to populate a selectlist.
These queries only return data relevant for the selected organisation.
After that there is a dropdownlist to select which selectlist should be displayed. This will populate another dropdownlist with the data returned from the query.
On the initial load it is loaded correctly for the first organisation. However when another organisation is selected, an ajax post will call a method. this will run the queries succesfully and set the properties to the returned lists. however the problem is that the razor page still uses the data from the initial load.
this results in the fact that whatever organisation i will select, it will use the data from the queries for the first organisation on the razor page.
below the ajax call
$.ajax({
method: "POST",
url: "/Aanleveringen/Create?handler=Filter",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json",
data: { organisatieId: $('#ddlOrganisatie option:selected').val() },
success: function (msg) {
alert(msg);
},
error: function (req, status, error) {
alert("Error try again");
}
});
and the method:
[HttpPost]
public IActionResult OnPostFilter(int organisatieId)
{
Filter filter = new Filter();
Organisatie organisatie = _context.Organisatie.Distinct().Where(x => x.Id == organisatieId).First();
FilterWaardeGemeente = filter.GetFilterGemeente(organisatie);
FilterWaardeDienst = filter.GetFilterDienst(organisatie);
FilterWaardeClient = filter.GetFilterClient(organisatie);
return new JsonResult("Gelukt");
}
looking for any suggestion to have the razor page model update with the most recent c# pagemodel.
thanks in advance.
Changing your model isn't going to do anything, as the Razor page is not being re-rendered. Since you're making the request via AJAX, you need to return your select list items from that action, and then use JavaScript to update the select list options manually in the DOM.
I have created an auto-populated drop downlist on my MVC 4 web application. When the user selects an item from the dropdown list, I want the partial view to show the item selected rather than all items as it already displays in this partial view.
How do I pass the string value parameter of the selected list item from an auto-populated dropdown list to a partial view controller?
Here is the code for my auto populated dropdown list:
#foreach (var m in ViewDatamodel)
{
if (m.State == "In Work")
{
<li>#m.TargetName</li>
}
}
I want to pass the m.TargetName string as a parameter so that i can manuipulate the partialview based on which list item is selected. The partialview consists of progress bars for jobs being performed where the data is stored on a SQL Server DB. I use the following Ajax Script to refresh the original partial view every 3 seconds. I need to be able to do the same with the selectedd partial views. Again, this is all autopopulated, so I am assuming the best way is to go by the TargetName:
<script>
function loadpartialView() {
$.ajax({
url: '#Url.Action("_GetfoeStatus', "Status")',
type: 'POST',
data: '{}', //I am assuming that I will need to pass the parameter to here
cache: 'false',
async: 'true',
success: function (result) {
$('#progress').html(result);
}
});
}
$(function() //..... Refresh Timer
Both the Action and RenderAction methods have overloads that allow you to pass additional parameters that are appended to the query string for the resource.
If you are doing this on the server side, you can:
Html.RenderAction("_GetForStatus", "Status", new { TargetName = m.TargetName })
If you are doing this on the client side, you would have to write some additional jQuery to make it work (or just plain old Javascript).
function loadpartialView() {
$.ajax({
url: '#Url.Action("_GetfoeStatus', "Status")',
type: 'POST',
data: { TargetName: $("#YourDropDown").val() }
cache: 'false',
async: 'true',
success: function (result) {
$('#progress').html(result);
}});
}
I used "TargetName" because I didn't know what your parameter name is.
Hi fellow programmers,
I have a database with some data. I Created a WCF Service that uses jQuery Autocomplete to get all names from the database. I get response with JSON but I want to display this in the autocomplete.
This is what my jQuery looks like:
$(function () {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#city").autocomplete({
source: function (request, response) {
$.ajax({
url: "/service.svc/GetData",
dataType: "jsonp",
data: {
DataName: request.term
},
success: function (data) {
response(data);
}
});
},
minLength: 3,
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 am fairly new to WCF and want to know what the next step is? How do I map the data so I can display it?
The JSON data output looks like this:
{"GetDataResult":[{"Name":"Fran $","CategoryId":102,"dataId":1,"IndexId":16,"InsertedDate":null,"Manual":false}
The autocomplete widget expects the array you supply to the response callback function to be in one of the following formats:
An array of strings, e.g. ["Hello", "Goodbye"]
An array of objects. Each object must have at least either a label property or a value property. It may have other properties as well.
So in your situation you can either:
Edit the server-side code that returns the JSON to conform to the format that the widget expects, or
Modify the results before passing them on to the response callback.
I'll focus on #2. The canonical way to do this is to use $.map to transform the array you got back from the server into the correct format, and then supply the resulting array to the response callback.
In your case that could look something like this:
success: function (data) {
response($.map(data.GetDataResult, function (item) {
return {
label: item.Name,
value: item.dataId
};
}));
}
Example: http://jsfiddle.net/yntrp063/
Note that the value property's value will be used inside of the textbox after you select an item--that might not be what you want.
I am facing a weird problem. I have a cshtml form:
<label class="pre_req_questions_width">
#Html.RadioButton("radioGroup" + Model.ID, "1", (Model.ExpectedResponse == 1 ? true : false), new { id = "rbtnYes", style = "margin-top:0px; margin-right:10px;" })Yes</label>
<label class="pre_req_questions_width">
#Html.RadioButton("radioGroup" + Model.ID, "2", !(Model.ExpectedResponse == 1 ? true : false), new { id = "rbtnNo", style = "margin-top:0px;margin-right:10px;" })No</label>
On form submit, I am getting radio group value like this:
int radioValue = int.Parse(fc.GetValue(controlID).AttemptedValue);
It works fine when i call it from #Html.BeginForm(), but when i try to send form collection via ajax like this:
input = $(':input')
$.ajax({
type: "POST",
url: '#Url.Action("SavePrerequisiteQuestion", "Dashboard", new { id = #Model.ID })',
data: input,
dataType: "html",
success: function (msg) {
alert("fine");
}, error: function (req, status, error) {
// with error
alert(error);
}
});
It send both values like this "1,2" rather than sending just selected/submitted value.
In your ajax request, you're sending all :input elements as your data:
...
data: input
...
What you probably want is to just serialize your form data, and send it with the request:
...
data: input.closest('form').serialize()
...
This is assuming you have your radio buttons in a <form> tag.
It may not be so easy to work around this. For instance, to get a selected radio button, you can do this: jQuery get value of selected radio button
So you can't just take all inputs and get the values from them... instead, you have to have more of a selective approach, and handle different elements appropriately. Checkboxes and selects will also have a similar problem.
You can put the #Html.Beginform back in and hijack the form submit in your jQuery
$('#formID').on('submit', function(e){
e.preventDefault(); // Just to stop the automatic Non Ajax submission of the form
$.post($(this).attr('action'), $(this).serialize(), function (data) {
//do stuff on success callback
alert("fine");
});
});
You can inherit the action path from the Html.BeginForm itself in the path below by doing
$(this).attr('action')
Note: If you want to manually put the path in there you still can instead of getting it
from the form
Then use $(this).serialize() to just serialize the whole form like the person above me
suggested
Inside my controller there is JsonResult action which returns me a list of House object.
I want onclick using ajax to retrieve these data and to display json data inside my view.
Inside firebug I'm able to see proper Response and Json result but I dont know how to display inside my view.
function GetTabData(xdata) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id: xdata }),
success: function (result) {
// tried with these but it doesnt work
// result = jQuery.parseJSON(result);
// alert(result.Title);
},
error: function () { alert("error"); }
});
}
public JsonResult GetTabData()
{
...
var temp = getMyData...
return Json(temp, JsonRequestBehavior.AllowGet);
}
// View page
<div id="showContent">
// Json data should appear here
</div>
Inside firebug JSON tab when success:function(result) is empty
I have following data:
Id 149
PropertyType "Apartment"
StreetNumber "202B"
CityName "Sidney"
Title "My test data"
success: function (json) {
var data = null;
$.each(json.items,function(item,i){
data = '<div>'+item.Id+ ' ' + item.CityName +'</div>';
$("#showContent").append(data);
});
}
First of all, you can specify the dataType attribute in your ajax call to 'json' and then don't have to decode the json response again -
dataType: 'json'
Then, you don't need to use parseJSON. Simply use result.Title etc.
success: function (result) {
alert(result.Title);
var showContent = $('#showContent');
showContent.html(result.Id+','+result.Title);
},
EDIT: As Mukesh said, you can have the ajax function return json without using any extra decoding.
The ajax call result is already an object. You can do whatever you want with it it inside the success function.
For example you could create a table of the information dynamically inside the function, or send the data to another function by calling the function inside that success function. Once you leave the success function, the data is not usable anymore.
Access the data object like any object (data.someProperty).