Select field is not showing the dropdown values - javascript

Can anyone please help me, I am stuck with this past two days. I am new to Knockoutjs / viewmodel. I am trying to understand how bind the data to the dropdownlist. The dropdown values needs to be pulled from the DB through the API depending on the value entered in another field (which is basically the input parameter for the API to return the dropdown values). The API to return the data is like below
[HttpPost]
public JsonResult GetGInfo(string sNumber)
{
try
{
DSRepository dsr = new DSRepository();
List<String> gTypeList = dsr.GetDDInfo(sNumber);
if (gTypeList != null)
return Json(gTypeList);
else
return null;
}
catch (Exception e)
{
return null;
}}
Below are the two fields
// this value should be passed in to the API to retrieve the dropdown list
self.sNumber= ko.observable().extend({ required: { params: true, message: "Required!" } });
//Dropdown list field
self.gType= ko.observable().extend({ required: true });
//function for making a call to the API
self.getGTypes = function (data, event) {
$.ajax({
url: '/REQ/GetGInfo',
type: 'POST',
data: {
sNumber: self.sNumber()
},
success: function (response) {
if (response.length < 1)
console.log("Record retrieved successfully");
},
error: function (errorThrown) {
console.log("Error retrieving the record");
}
})
};
And UI is like below
<div class="form-group required">
<label for="SNumber" class="control-label">SNumber:</label>
<input type="number" id="SNumber" class="form-control" data-bind="event: {change: getGTypes}, value: sNumber">
</div>
<div class="form-group required">
<label for="GType" class="control-label">GType</label>
<select id="GType" name="GType" class="form-control" data-bind="options: getGTypes, value: gType, optionsCaption: 'Select'"></select>
</div>
</div>
So when the value is entered in the SNumber field the getGenoTypes is called I see that the data is returned from the API through the debugging, for the number I entered I see that below data gTypeList is returned back from API
But in the dropdown I see nothing
Please help me what is that I am missing here totally stuck

You need to actually save the dropdown values that you receive from the API on your viewmodel. You can't just execute the API call and expect Knockout to magically understand it needs to use the (asynchronous) response data to populate the select list.
So basically, you need to do something like this:
// this value should be passed in to the API to retrieve the dropdown list
self.sNumber = ko.observable().extend({ required: { params: true, message: "Required!" } });
//Dropdown list field
self.gType = ko.observable().extend({ required: true });
// Dropdown list values
self.gTypes = ko.observableArray();
//function for making a call to the API
self.getGTypes = function (data, event) {
$.ajax({
url: '/REQ/GetGInfo',
type: 'POST',
data: {
sNumber: self.sNumber()
},
success: function (response) {
self.gTypes(response);
},
error: function (errorThrown) {
console.log("Error retrieving the record");
}
})
};
<select id="GType" name="GType" class="form-control" data-bind="
options: gTypes,
value: gType,
optionsCaption: 'Select'"></select>
Note that I don't know what response looks like so this is probably not 100% correct, but I hope you get the idea of it.

Related

How to use select2 with multiple options using Razor and MVC

I am trying to create a multiple choice list using Select2, Razor and the MVC framework. My problem is that the object in the controller that receives the array input is always null. The front-end looks as follows:
<form class="form-horizontal" method="post" action="#Url.Action(MVC.Configurazione.Contatori.Edit())">
<div class="form-group">
<div class="col-lg-8">
<select class="form-control attributoSelect2" name="attributiSelezionati" value="#Model.AttributiSelezionati">
<option value="#Model.AttributiSelezionati" selected>#Model.AttributoDescrizione</option>
</select>
</div>
</div>
</form>
The action method "Edit", is the controller method that receives the array of chosen items from the drop-down list.
The Javascript is the following:
$('.attributoSelect2').select2({
placeholder: "Search attribute",
multiple: true,
allowClear: true,
minimumInputLength: 0,
ajax: {
dataType: 'json',
delay: 150,
url: "#Url.Action(MVC.Configurazione.Attributi.SearchAttrubutes())",
data: function (params) {
return {
search: params.term
};
},
processResults: function (data) {
return {
results: data.map(function (item) {
return {
id: item.Id,
text: item.Description
};
})
};
}
}
});
And finally the C# controller has an object that is expected to retrieve the data from the view and is defined:
public string[] AttributiSelezionati { get; set; }
and the HttpPost method that receives the data is:
[HttpPost]
public virtual ActionResult Edit(EditViewModel model) { }
Could someone give me some insight into what I am doing wrong and the areas that I should change in order to find the problem?
you class name error not attributoSelect2 is attributesSelect2 , I also make this mistake often. haha
<select class="form-control attributoSelect2" name="attributiSelezionati" value="#Model.AttributiSelezionati">
<option value="#Model.AttributiSelezionati" selected>#Model.AttributoDescrizione</option>
</select>
There are multiple reason for not being receiving data on server. First of all you need to change your select code as follow
#Html.DropDownList("attributiSelezionati", Model.AttributiSelezionati, new { #class = "form-control attributo select2" })
now go to console in browser and get the data of element to confirm that your code properly works in HTML & JS
After that you need to add attribute at your controller's action method as
[OverrideAuthorization]
[HttpPost]
You can try the following approach that has been used in some of our projects without any problem:
View:
#Html.DropDownListFor(m => m.StudentId, Enumerable.Empty<SelectListItem>(), "Select")
$(document).ready(function () {
var student = $("#StudentId");
//for Select2 Options: https://select2.github.io/options.html
student.select2({
language: "tr",//don't forget to add language script (select2/js/i18n/tr.js)
minimumInputLength: 0, //for listing all records > set 0
maximumInputLength: 20, //only allow terms up to 20 characters long
multiple: false,
placeholder: "Select",
allowClear: true,
tags: false, //prevent free text entry
width: "100%",
ajax: {
url: '/Grade/StudentLookup',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.Name + " " + item.Surname
});
});
return { results: newData };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }
});
//You can simply listen to the select2:select event to get the selected item
student.on('select2:select', onSelect)
function onSelect(evt) {
console.log($(this).val());
}
//Event example for close event
student.on('select2:close', onClose)
function onClose(evt) {
console.log('Closed…');
}
});
Controller:
public ActionResult StudentLookup(string query)
{
var students = repository.Students.Select(m => new StudentViewModel
{
Id = m.Id,
Name = m.Name,
Surname = m.Surname
})
//if "query" is null, get all records
.Where(m => string.IsNullOrEmpty(query) || m.Name.StartsWith(query))
.OrderBy(m => m.Name);
return Json(students, JsonRequestBehavior.AllowGet);
}
Hope this helps...
Update:
Dropdown option groups:
<select>
<optgroup label="Group Name">
<option>Nested option</option>
</optgroup>
</select>
For more information have a look at https://select2.org/options.

Storing HTML form input in a JS object

I know there is a very similar question asked over here but my object hierarchy is different than the one in that question.
Anyways, I want to store the HTML form input data in to my JavaScript object. Here is my HTML form code:
<form id="newAuction">
<input id="title" name="title" required type="text" value="" />
<input id="edate" name="edate" required type="datetime" value="" />
<input id="minbid" name="minbid" required type="number" value="" />
<button class="btn btn-primary">Submit</button>
</form>
What I want is to get the values of these 3 inputs and store it in my JS object.
I know the proper JSON format needed to post the data to my API. (I tried POSTing with POSTman and I get a status 200, so it works). The proper format is:
{
"auction": {
"Title": "Auction1",
"EDate": "01/01/1990",
"MinBid": 30
},
"productIds": [1,2,3]
}
This is what my JS object looks like:
<script>
$(document).ready(function() {
var vm = {
auction: {},
productIds: []
};
//validation and posting to api
var validator = $("#newAuction").validate({
//assigning values
vm.auction.Title = document.getElementById('title').value;
vm.auction.MinBid = document.getElementById('minbid').value;
vm.auction.EDate = document.getElementById('edate').value;
vm.productIds.push(1);
submitHandler: function () {
$.ajax({
url: "/api/newAuction",
method: "post",
data: vm
})
.done(function () {
toastr.success("Auction Added to the db");
//setting the vm to a new vm to get rid of the old values
var vm = { auction: {}, productIds: [] };
validator.resetForm();
})
.fail(function () {
toastr.error("something wrong");
});
return false;
}
});
});
</script>
As you can see, I am using document.getElementById('title').value; to get the values and assign them but I'm getting the syntax error Expected : Comma expected
Not sure if this matters, but this is inside a .NET MVC5 project.
Move your value assignment set of codes inside submitHandler. Check the syntax of validate() https://jqueryvalidation.org/validate/
//validation and posting to api
var validator = $("#newAuction").validate({
submitHandler: function () {
//assigning values
vm.auction.Title = document.getElementById('title').value;
vm.auction.MinBid = document.getElementById('minbid').value;
vm.auction.EDate = document.getElementById('edate').value;
vm.productIds.push(1);
$.ajax({
url: "/api/newAuction",
method: "post",
data: vm
})
.done(function () {
toastr.success("Auction Added to the db");
//setting the vm to a new vm to get rid of the old values
var vm = { auction: {}, productIds: [] };
validator.resetForm();
})
.fail(function () {
toastr.error("something wrong");
});
return false;
}
});

Disable button unless Selected from Typeahead Autocomplete

--- EDIT: Explaining the Flow ---
In the input field, the user is supposed to enter any string which is basically the name of a company they are searching for. Once the user has entered 3 or more characters, an AJAX call goes to the database, and fetches results matching the users query and displays them like search suggestions in Google or your browser URL bar. One the user selects an item from the suggestions, and clicks on the button, a function called setCompany() is triggered which performs different actions.
What I want is that the button which triggers further actions based on the search query, should be disabled UNTIL the user selects an item from the suggestions that Bloodhound, Typeahead has come up with.
--- End EDIT ---
I am using the code below to enable user to select values from the dropdown list that is generated by Typeahead, Bloodhound.
$(document).ready(function() {
//Set up "Bloodhound" Options
var my_Suggestion_class = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('keyword'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "{{ URL::to('user/company/%compquery') }}",
filter: function(x) {
return $.map(x, function(item) {
return {keyword: item['name']};
});
},
wildcard: "%compquery"
}
});
// Initialize Typeahead with Parameters
my_Suggestion_class.initialize();
var typeahead_elem = $('.typeahead');
typeahead_elem.typeahead({
hint: false,
highlight: true,
minLength: 3
},
{
// `ttAdapter` wraps the suggestion engine in an adapter that
// is compatible with the typeahead jQuery plugin
name: 'results',
displayKey: 'keyword',
source: my_Suggestion_class.ttAdapter(),
templates: {
empty: 'No Results'
}
});
});
Here is the HTML:
<div class="iner-sub-header" style="border-bottom: 1px solid #ccc;">
<div class="row" style = "background-color: white;">
<div class="col-md-12 heading">
<div id = "results" class="col-md-12 col-xs-12 results">
<span class="glyphicon glyphicon-search span-search" aria-hidden="true"></span>
<input type="search" class="typeahead custom-input-padding" placeholder="Search Company" id="keyword" onselect="setCompany();">
<button class="btn go-btn" id="go" onclick="setCompany()">SEARCH</button>
</div>
</div>
</div>
</div>
I want to make sure that the button that will trigger setCompany() funtion is disabled until the user selects something from the dropdown that is generated by Typeahead.
Can anyone please help me out?
Try
html
<button class="btn go-btn" id="go" onclick="setCompany()" disabled="true">SEARCH</button>
js
typeahead_elem.bind("typeahead:select", function(ev, suggestion) {
$("#go").prop("disabled", false);
});
See disabled , typeahead.js - Custom Events
This made it work for me. Now its working perfectly.
$(document).ready(function() {
//Set up "Bloodhound" Options
var my_Suggestion_class = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('keyword'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "{{ URL::to('user/company/%compquery') }}",
filter: function(x) {
return $.map(x, function(item) {
return {keyword: item['name']};
});
},
wildcard: "%compquery"
}
});
// Initialize Typeahead with Parameters
my_Suggestion_class.initialize();
var typeahead_elem = $('.typeahead');
typeahead_elem.typeahead({
hint: false,
highlight: true,
minLength: 3
},
{
// `ttAdapter` wraps the suggestion engine in an adapter that
// is compatible with the typeahead jQuery plugin
name: 'results',
displayKey: 'keyword',
source: my_Suggestion_class.ttAdapter(),
templates: {
empty: 'No Results'
}
}).on("typeahead:selected typeahead:autocompleted", function(ev, my_Suggestion_class) {
$("#go").prop("disabled", false);
});
});
I wanted a way to re-disable the button if the button if the textbox's content changes and isn't a typeahead selected value. On typeahead:select I store the display text. On every key up I ensure the text still matches the stored variable. Otherwise I disable the button again.
this.searchbox = $('.js-patient-search');
this.searchbox.typeahead({
hint: true
}, {
source: Bloodhound,
display: function(obj) {
return obj.first_name + ' ' + obj.last_name;
}
});
this.searchbox.on('typeahead:select', (function(_this) {
return function(e, suggestion) {
_this.displayName = _this.searchbox.val();
return $('.js-add-encounter').prop('disabled', false);
};
})(this));
return this.searchbox.keyup((function(_this) {
return function(e) {
if (_this.searchbox.val() !== _this.displayName) {
return $('.js-add-encounter').prop('disabled', true);
}
};
})(this));
NOTE: This is parsed coffeescript but I think it should be fairly clear what's going on.

passing value from javascript to ajax in mvc4

i need to select a value from a grid and pass it to ajax. I'm getting the error as "Id undefined". can anyone suggest me a solution for this issue. Records most be deleted which a presented in grid. on clicking the button selected value must got to ajax function for deletion process. value s moved to ajax but getting error that the policyid is undefined Thanks in advance.
Code of grid column:
#{
var grid = new WebGrid(Model.Policy, rowsPerPage: 20, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridcal");
grid.Pager(WebGridPagerModes.NextPrevious);}
#grid.GetHtml(
tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
columns:
grid.Columns(
grid.Column("PolicyName","Policy Name",style: "colWidth"),
grid.Column("PolicyValue","Policy Value",style: "colWidth"),
// grid.Column ("Delete",format:#<text><img src="~/Images/img-delete-blk-icon.png" width="9" height="9" alt="Delete"/> </text>)
****grid.Column(format: #<text><input type="image" onclick="AJAXCall_Fun_DeletePolicy()" src="~/Images/img-delete-blk-icon.png" name="image" width="9" height="9" /></text>)****
))
#if (grid.HasSelection)
{
<b>Policy Name</b>#AppliedPolicies.PolicyName<br />
<b>Policy Value</b>#AppliedPolicies.PolicyValue<br />
}
Ajax :
function AJAXCall_Fun_DeletePolicy() {
if ($.xhrPool.length > 0) {
$.each($.xhrPool, function (idx, jqXHR) {
if (jqXHR) {
this.abort();
}
});
$.xhrPool = [];
}
var PolicyId = PolicyId();
if (PolicyId.length > 0) {
$.ajax({
type: "GET",
url: "/Roles/DeletePolicy",
data: { 'PolicyId': JSON.stringify(PolicyId) },
async: true,
cache: false,
datatype: "json",
Controller code:
public JsonResult DeletePolicy(string PolicyId)
{
bool status = false;
using (clsBLLGroups objclsBLLGroups = new clsBLLGroups())
{
status = objclsBLLGroups.DeletePolicy(UserCookieWrapper.UserAccessToken, PolicyId.ToString());
}
return Json(status, JsonRequestBehavior.AllowGet);
}
a web grid renders as a table so use Get id of selected row in a table -HTML to get the id of clicked row and you can pass that through your ajax call to the controller.
You mentioned PolicyId is controller code. If you want to include a value from your model in your ajax call you just need to use #
var PolicyId = '#(Model.PolicyId)';
you can use that for your url as well. We use
url: '#Url.Action("DeletePolicy", "Roles")',
for our url. Hope this helps

I want to filter in the list if the text box value is changed using knockout

I want to filter in the list if the text box value is changed if the
JSON Returned in Ajax call is as I am using two different model.
Filteration should show hide or just filter the data I am providing you the JSON data what I am getting from the ajax call. Thanks
Data = [{"code":"Grand Financial","cls":"Branch","Chk":true},{"code":"Joan Group","cls":"Branch","Chk":true}]
var searchModel, advisorGroupModel;
$(document).ready(function () {
$.ajax({
type: "GET",
url: '/ASPNET/Reports/GetAdvisorGroups',
dataType: "json",
success: function (data) {
advisorGroupModel = {
advisorGroup: ko.observableArray(data)
};
ko.applyBindings(advisorGroupModel, document.getElementById("advisorGroupModel"));
}
})
var searchModel = {
searchQuery: ko.observable('')
};
searchModel.searchHandle= ko.dependentObservable(function () {
var code = this.searchQuery().toLowerCase();
return ko.utils.arrayFilter(advisorGroupModel, function (beer) {
debugger;
return beer.code.toLowerCase().indexOf(code) >= 0;
});
console.log(search);
}, searchModel)
ko.applyBindings(searchModel, document.getElementById("searchModel"));
});
<div id="searchModel">
<input data-bind="value: searchQuery, valueUpdate: 'keyup'" />
<h6 data-bind="text: searchQuery"></h6>
</div>
<div class="CheckBoxListGroup" id="advisorGroupModel">
<ul data-bind="template: { name: 'advisorGroupTemplate', foreach: advisorGroup, as: 'singleAdvisorGroup' }"></ul>
<script type="text/html" id="advisorGroupTemplate">
<li>
<input type="checkbox" data-bind="attr: { value: code, id: code, checked: Chk }" name="GroupsSel">
<label data-bind="attr: { for: code }, text: '' + code + ' (' + cls + ')' "></label>
</li>
</script>
</div>
don't bind your display to the entire list, bind your display to a computed function that returns the filtered list or returns all items when there are no filters.
then on your keyup call your filterlist function that filters the list removing the ones that do not match your filter

Categories

Resources