knockout.js,asp.net-mvc-5,web-api , Why is KnockoutJS not showing the same number of objects as my Web API controller?


Why is KnockoutJS not showing the same number of objects as my Web API controller?

Question:

Tag: knockout.js,asp.net-mvc-5,web-api

The solution was the same as in this question: How to get an observableArray's length?

...but the question itself is unique so anyone in the same situation will hopefully have an easier time finding the answer than I did.

I'm fairly new to Knockout and to Web API. I've built the following based upon similar code I found in a few different tutorials.

function MyViewModel()
{
    var self = this;
    self.objects = ko.observableArray([]);

    $.getJSON("http://localhost:XXXX/api/getobjects", function (data,status,xhr) {
        self.objects(data);
        alert(xhr + " " + status + ", " + "Objects returned: " +  self.objects.length);
    }
}

ko.applyBindings(new MyViewModel());

In my controller, my goal is to filter objects from a table in my database by a MatchingId that matches the current user's Id. I have this in my controller:

public IQueryable<myObject> GetObjects()
{
    this.ApplicationDbContext - new ApplicationDbContext();
    this.UserManager = new UserManager<ApplicationUser>(this.ApplicationDbContext));
    var user = UserManager.FindById(User.Identity.GetUserId());

    var query = db.MyObjects.Where(a => a.MatchingId == user.Id);

    return query;
}

I've stepped through and confirmed that my query is successfully pulling the desired records from the database, yet the response received on the client side is empty. Here is the output of my alert:

alert(xhr + " " + status + ", " + "Objects returned: " + self.objects.length);

// yields this:
// "200 success, Objects returned: 0"

There were four valid objects in my query on the server-side. Can anyone help me figure out why they didn't transfer through?


Answer:

ko.observableArray does have a length property, but it is the property of the observableArray function itself, not of the array:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length

To get the length of the enclosed array, invoke observableArray then call length: self.object().length. For example in your code, change your alert to:

alert(xhr + " " + status + ", " + "Objects returned: " + self.objects().length);

and that should give you the '4' you're after.

Ref: How to get an observableArray's length?


Related:


MvcSiteMapProvider - Enhanced bootstrap dropdown menu


c#,twitter-bootstrap,asp.net-mvc-5,mvcsitemapprovider,mvcsitemap
I'm trying to build a menu like this: For reference I'm using this library https://github.com/behigh/bootstrap_dropdowns_enhancement @Html.MvcSiteMap().Menu("BootstrapMenuHelperModel") @model MenuHelperModel <nav class="navbar" role="navigation"> <div class="container-fluid menu-container"> <div class="collapse navbar-collapse"> <div class="navbar-header"> <span class="navbar-brand">FAR BACKOFFICE</span> </div> <ul class="nav nav-pills"> @foreach (var node in Model.Nodes) { if...

Knockout JS Validation not working


javascript,asp.net-mvc,knockout.js
I am a newbie in Knockout JS. i want to apply validations in KO. i have used plugin knockout.validation.min.js . I have implemented it like this but not working My View Model $(document).ready(function myfunction() { ko.applyBindings(new EmployeeKoViewModel()); }) var EmployeeKoViewModel = function () { var self = this; self.EmpId =...

Embedding a Silverlight App into a MVC


c#,asp.net-mvc-5,silverlight-5.0
I decided to convert the WPFs into a Silverlight applications. My only problem is trying to get it to display the silverlight application in my MVC web browser. I added all of my silverlight projects into my MVC project. I am just not getting it to show my silverlight application....

What is difference between Init and update function of knockout js custom binding


knockout.js
i like to know what is difference between Init and update function of knockout js custom binding ? when we should write code inside init function and when we should go for update function of knockout js custom binding. i go through knockout js doc but still my understanding for...

knockout js css biniding doesn't save changes


javascript,knockout.js
knockout js css biniding doesn't save changes after div's class was changed: My model contain 2 properties: man: '', woman: 'active' And I have 2 element in dom, which classes can be changed. <input type='button' value='Is MAN?' class='' data-bind='css: man'> <input type='button' value='Is WOMAN?' class='' data-bind='css: woman'> I want to...

Getting users from another AD Domain using PrincipalContext


c#,asp.net,active-directory,asp.net-mvc-5,active-directory-group
How would I get users from an AD Group which contains users from different domains. For example, I have 2 domains in my active directory, Domain1.corp.com and Domain2.corp.com I have an AD group called TestGroup which contains users from both the domains. Domain1 users: TestUser1, TestUser2 Domain2 users: TestUser3, TestUser4,...

How can I make Kendo UI Panelbar “skip” an element when reading an HTML list?


html,knockout.js,kendo-ui,kendo-panelbar
I'm using Knockout.js 3.3 and utilizing components with custom elements. I am trying to use Kendo UI's Panelbar with that list. The only problem is, it fails (the nested <ul> won't expand) because my lists are in the following format: <ul> <sidebar-step> <li>some message <ul> <li>some sub message<li> <li>another sub...

knockout binding for datepicker with dynamic options


knockout.js,jquery-ui-datepicker
I am using knockout binding for jquerry date picker. refer http://stackoverflow.com/questions/6612705/jquery-ui-datepicker-change-event-not-caught-by-knockoutjs the same code is working fine except i cant set datepicker options dynamically. How to set datepicker option(like mindate max date etc) dynamically(button click) using the the above reference link....

Automatically call a click handler to load a jQuery dialog box on page load


javascript,jquery,knockout.js
I've got a page, on the page there is a button wrapped in an anchor tag: <a href="javascript:void(0)" data-bind="click: AddNewThread, text: 'Add New Discussion'" class="btn new"></a> This calls a function labeled as AddNewThread, now this function opens up a dialog Box using jQuery, and in the dialog box there is...

Knockout subscription insight: detecting if disposed


knockout.js,subscriptions,singlepage
I have a subscription management in my ko model, which saves any subscription by intercepting them and saving reference to them. I then dispose() them, but I need to understand sometimes if a sub is already disposed. Is the member Gb, a boolean of the subscription object, an active-inactive flag?...

How to use current object in a computed observable? — Knockout.js


javascript,jquery,knockout.js
I have a foreach data-binding on an array. I want to access the current object or place in the computed observable (as it happens with the click data-binding). Example: Here is my View: <tbody data-bind='foreach: items'> <tr data-bind="attr: {class:$root.changeClass()}"> <td data-bind='text: name'></td> </tr> </tbody> And, here is the view-model: function...

Convert string value to english word


c#,asp.net-mvc-5
I'm trying to figure out / where to start in regards to this situation say for example I enter $127.45 in to a textbox I would expect the application to spit back one hundred and twenty-seven dollars and forty-five cents The word will then be placed on a document and...

In a table which is data bound using knockout how to dynamically select any column values from view model


jquery,knockout.js
I've a view model which I am binding to the view- JSFiddle link to the code- http://jsfiddle.net/piyush4bpl/9kq2t5xu/ In the view model, I've two arrays- grid, kpis I am binding 'kpis' in to drop downs options. 'grid' is an array which has 4 properties named as 'Promoters', 'Positive', 'Negative', 'Neutral'. 'kpis'...

How do I properly send __RequestVerificationToken with an ajax request in MVC5


ajax,asp.net-mvc,asp.net-mvc-5
I'm trying to send an ASP.NET AJAX request to my application. In the application's controller, I have: [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "ID,Name,Instructions,Glass,Notes")] Drink drink, [Bind(Include= "ID,Amount,Brand,IngredientID,DrinkID")] IEnumerable<DrinkIngredient> DrinkIngredients) { if (ModelState.IsValid) { //and so on my javascript looks like this: console.log($('#editDrinkForm').serialize()) var x = new XMLHttpRequest(); x...

MVC/Razor: Error at Viewbag.Title


c#,asp.net-mvc,razor,asp.net-mvc-5
I have two methods: public ActionResult Index() { var propList = db.Properties .Where(x => x.SiteVisibilityFlags.HasFlag(Enums.SiteVisibilityFlags.Corporate) || (x.SiteVisibilityFlagsOverride == true && x.SiteVisibilityFlagsOverrideValue.HasFlag(Enums.SiteVisibilityFlags.Corporate))) // just ones visible to 'Corporate' .ToList(); // Use view model var pDVMs = DomainModelsToViewModels(propList); return View(pDVMs); } public ActionResult Region(string id) // (regionId/marketId) { // make sure to...

Horizontal image list modules to be used wit KO.js and Bootstrap


jquery,twitter-bootstrap,knockout.js
I'm evaluating how to implement a UI with Knockout.js and Bootstrap. Basically, what I want to achieve is a horizontal list of images, (ideally scrollable) where each image also has an information frame. The list is populated from KO-observableArray. <div data-bind="foreach: thumbnails"> <span> <a href='#' data-bind='click: select '> <img width="120"...

Modal from inside Bootstrap Tabs using Knockout foreach


jquery,twitter-bootstrap,knockout.js,twitter-bootstrap-3
I have Bootstrap tabs bound to a KnockoutJS observable array using a foreach binding, which is working fine. I now want to launch a Bootstrap modal from inside the active tab. <div class="tab-content"> <!-- ko foreach: trueData --> <div class="tab-pane fade in" data-bind="css:{active: $index() == 0}, attr :{'id': 'tab' +...

Knockout js unable to bind data using observableArray


knockout.js,asp.net-mvc-5
I am trying to display all the employees in the database and I am unable to achieve it. My JS, var EmployeeKoViewModel = function () { var self = this; self.EmpId = ko.observable(""); self.Name = ko.observable(""); self.City = ko.observable(""); self.Employees = ko.observableArray([]); GetEmployees(); function GetEmployees() { $.ajax({ type: "GET", url:...

MVC: after export to excel, index action result is not getting called


asp.net-mvc-5,export-to-excel
I have one MVC application, in which export to excel functionality is given. I want to redirect Index action once export is finished. I have written below code but it not redirected to index action. what i missed here ? output = new MemoryStream(); workbook.Write(output); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",...

How to get routevalues from URL with htmlhelpers or JavaScript?


javascript,asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-routing
I have this MVC MapRoute routes.MapRoute( name: "Authenticated", url: "{controller}/{action}/{foo}/{bar}", defaults: new { controller = "Home", action = "WelcomePage", Foo = "0", Bar = "0" } ); And URL http://localhost/mysite/controller/action/2/1 How can I with JavaScript recieve the 2 and 1? I would prefer a solution with as little substring work...

Best approach to upgrade MVC3 web app to MVC5?


c#,.net,asp.net-mvc,asp.net-mvc-5
I have a web application which runs on Azure which is currently running MVC3/C#, EF6.1, .NET4.5. I would like to upgrade it to MVC5 to be: a) Current b) Get benefit of new features c) Get Performance gains. This is a part of a performance project, so hopefully there will...

button click to set an optionsCaption value as default in knockout


knockout.js
I am currently working on options binding in knockout, the bindings is doing everything for me as per my requirement. But currently the problem I am facing is how to set optionsCaption Value again to my Select Box on a button click. Here is my code var clickMe = function(){...

Inherited Property of Model is always returning Null Value


c#,asp.net,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-5
I have a view which displays a radiobutton list on left side of the page and it also loads a partialview on right side of the page which consist of various filters to be selected before displaying a report in a popup window. The problem is that the property named...

Why doesn't CSS transition get applied?


javascript,html,css,knockout.js
I've built a small stacked bar visual just using floated divs that underneath is bound to some data using knockout. What I want to be able to do is to animate changes in the size of these stacks when the data changes. I've managed to do this in the general...

string.Format is not giving correct output when INR currency symbol (Rs.) come to display


c#,asp.net-mvc-5,devexpress
While display bank transaction data to INR currency symbol (Rs.), output is not coming correct way. I need to display currency symbol along with 2 decimal points with thousand separator. I have tried so far1: column.PropertiesEdit.DisplayFormatString = string.Format("{0} #,0.00", Model.CurrencySymbol); I have used DevExpress MVC GridView. Current output when INR...

Linq Conditional DefaultIfEmpty query filter


c#,linq,asp.net-mvc-5,linq-query-syntax
I have a query as below: bool variable = false//or true var query = from e in _repository.GetAll<Entity>() from u in e.Users where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId from p in e.PractitionerProfiles.DefaultIfEmpty() select new { entity = e, user = u, profile = p }; This...

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?


asp.net-mvc,asp.net-mvc-4,razor,asp.net-mvc-5,claims-based-identity
I'm trying to learn Claims for MVC 5 OWIN login. I try'ed to keep it as simple as possible. I started with the MVC template and inserted my claims code (see below). I get an error when I use the @Html.AntiForgeryToken() helper in the View. Error: A claim of type...

How to append Urls in angular routing?


asp.net,angularjs,asp.net-mvc-5,angularjs-ng-repeat,angular-ui-router
How to do url(string) cocatenation in angular routing. Please refer the below snippet to understand my question. app.config(['$routeProvider', '$location'], function($routeProvider) { when('/', { templateUrl: '/AlbumsList.html', controller: 'a1Ctrl' }). when('/albums/:albumName', { templateUrl: 'AlbumsList.html', controller: 'b1Ctrl' }) }) app.controller('a1Ctrl', function($scope, $http) { $scope.albums = function() { //ajax getting data from server }...

Produce different serialized JSON for a given class in different scenarios


c#,json,serialization,asp.net-mvc-5,json.net
Update 1: for reasons I won't go into, I want to avoid having anything other than the properties to be persisted in my entity objects. This means no extra properties or methods... I have an entity called Entity1 with (say) 10 public properties. In one place in my code I...

Knokout select : Set Selected Item by item name not value


jquery,select,knockout.js
i have a knockout select as following observable Array issuingCountries 0: ObjectCoordinatorRegion: "EU" Country: "Australia" CountryId: 14 Id: 1 2: ObjectCoordinatorRegion: "AU" Country: "Japan" CountryId: 16 Id: 2 html <select class="issuing_country" data-bind="options: issuingCountries, optionsText : 'Country', value:IssuingcountrySelected, optionsCaption:'---Select---', " > </select> My question , i have { Country: "Japan" }...

Is it possible to inherit ko.computed to a prototype class?


javascript,knockout.js,observable
Let's say that I wish to have the behaviour a ko.computed has with: read write but I want to have an internal observable inside that ko.computed property, something like: this.a = ko.computed(function() { value: ko.observable(null), read: function() { return value; }, write: function(newValue) { if (newValue) { value(newValue); } }...

How to augment actionlink with route values at runtime with JavaScript in ASP.NET MVC 5?


javascript,asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing
I have this ActionLink. @Html.ActionLink("Link", "action", "controller", null, htmlAttributes: new {@class = "menuLink"}) I have to set routeValues to null because I don't know the value at compiletime. They are recieved from the selectedvalue of some dropdowns at runtime. Hence, I am trying to augment the routevalues at runtime with...

Modular Web Components with View-Based Data-Binding context


javascript,html,knockout.js,data-binding
I'm trying to make my code as modular as possible and mimic the patterns of WPF and Caliburn.Micro. Here's what I've tried so far using Knockout components. Component ViewModel function welcomeViewModel() { this.greeting = 'Hello world!; } App ViewModel function appViewModel() { this.firstGreetingVM = new welcomeViewModel(); this.secondGreetingVM = new welcomeViewModel();...

How to use ajax to post json string to controller method?


jquery,asp.net-mvc,visual-studio-2013,asp.net-mvc-5
I want to be able to post a json string to a control action but it's always receive the string as null. If I create a view model for the controller method, it works, but that's not what I want since there will be too much view models to maintain....

Check box in table header to check all checkboxes in other rows


jquery,knockout.js
I have a checkbox in my table header to select/unselect all checkboxes in the table.I tried to bind change/click event to that. same event is working for other check boxes but not for the check box on header. I am using MVC3 & KnockoutJS bindings. Added code part below. <tr...

Web API AuthorizeAttribute does not return custom response


c#,asp.net-web-api,asp.net-mvc-5
How can I make IsAuthorized return my custom object while function returns false? In my WebAPI project I have a class like; public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) { StandardWebAPIResponse invalidUserResponse = new StandardWebAPIResponse() { code = (int) Constants.ErrorCodes.InvalidCredentials, data = "InvalidCredentials.", StatusCode = HttpStatusCode.Unauthorized...

How to trigger ajax loading with an observable varariable in knockout?


ajax,knockout.js
I got some tabs in a page. When clicking on a tab, the currentTab changes its value, which should trigger an ajax loading of a new tab content. The concept is similar to a ko.computed, which however, only update another variable as the value change takes place. Is there any...

How to declare knockout component in typescript?


javascript,knockout.js,typescript
I am trying to follow example to create a component in knockout. http://knockoutjs.com/documentation/component-overview.html But I have to write a code in typescript. So how can I register component in knockout using typescript? What should I write in .ts file to convert it in something-like below. ko.components.register('like-widget', { viewModel: function(params) {...

How to trigger a function with textInput binding?


javascript,knockout.js
I'm using Knockout.js 3.3.0. In my viewmodel I have a lot of data rows that I present in a table with a foreach binding. In every row there is a text input that is bound to an observable. What I want to achieve is this: whenever the text changes, it...

Avoid error of cyclic value in view, knockout


javascript,json,knockout.js
My knockout model (version 3.3.0 of knockout) is something like this: var Node= function(id,name,parentNode) { var self = this; self.id= ko.observable(id); //more here... self.nodes = ko.observableArray([]); self.parentNode = parentNode; } When this model is bound to a view, knockout throws an error in the console (non-breaking error): TypeError: cyclic object...

MVC route attribute no controller


asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing
I'm building an intranet where I have the following home controller: [Route("{action=index}")] public class HomeController : Controller { public ActionResult Index() { return View(HomeModelBuilder.BuildHomeModel()); } public ActionResult FormsHome() { return View(HomeModelBuilder.BuildFormsHomeModel()); } } I'm trying to get my forms homepage to have a url of http://intranet/forms so I thought I...

Binding html to ko-observables.


knockout.js
In this example <strong>Test:</strong> <span data-bind="text: currentResult()? currentResult().test_name : '' " /><br/> <strong>SampleId:</strong> <span data-bind="text: currentResult()? currentResult().sample_id : '' " /><br/> I see only one text - only the first: Test: <test_name> If I exchange the lines, I see only SampleId:<my sample id> It is not because of height limits....

Knockout text binding showing the value


javascript,jquery,knockout.js
I am trying to text bind one element to a paragraph tag. It's not working properly and not giving any error in Browser. I am using Visual Studio for development. I created a fiddle for showing the problem and there i got the error that my binding is not defined....

How to upgrade mvc2 to mvc5?


asp.net-mvc,asp.net-mvc-2,asp.net-mvc-5
I've got an old project from a friend that he wants me to do redo. How ever that project is written in ASP.net mvc2. So When I try to open it in visual studio 2013 I can errors. Saying the file is incompatible. How would I go ahead and fix...

General function for observable array search


knockout.js
is there a way to do a general function for search an observable array and if the value found then set that object to another observable .? this question relate to Knokout select : Set Selected Item by item name not value so far i have tried self.getOptionByName = function(instance,opt,name){...

How detailed should your repository be? Testing issues [closed]


c#,unit-testing,asp.net-mvc-5
In my controller, I have something like this: class HomeController { [AllowAnonymous] public ActionResult Index() { HomeViewModel viewModel = new HomeViewModel(); viewModel.FieldSearchCriteria = new SearchCriteria(); viewModel.Blogs = this.unitOfWork.BlogRepository.GetAllPublishedBlogs(1, 2, "PublishDate", SortDirection.DESC, null).ToList(); viewModel.FieldWanteds = this.unitOfWork.FieldWantedRepository.GetAllFieldWanteds( 1, 2, "CreatedAt", SortDirection.DESC, null ).ToList(); viewModel.Fields =...

KnockoutJS custom component loader not executing `loadViewModel`


javascript,knockout.js,requirejs,knockout-components
Context I have been fiddling around and trying to create my own (just another) SPA framework. In this framework I've been trying to create a custom component loader to be able to do some dependency injection 'n stuff on the viewModels I'm loading. Used KnockoutJS version: 3.3.0 Problem The loadViewModel...

How can I add HTML to this Knockout.js Viewmodel variable? [duplicate]


javascript,html,knockout.js,knockout-components,knockout-templating
This question already has an answer here: HTML Entities with Knockout 1 answer I have a list of steps displayed on the page. Some steps (but not all) will have 1-3 substeps. I was thinking the simplest way of doing this was to just write the HTML manually within...

Checkbox to be checked on having value Y


asp.net-mvc,knockout.js
I have a checkbox bound to a viewmodel's observable property, whose value will be Y or N. I want the the checkbox to be checked when the value is Y and unchecked when the value is N. How to achieve this? I am able to achieve it if the value...