Is there a reason I would use Knockout MVC instead of Knockout JS?
Asked Answered
C

12

54

Another user suggested Knockout MVC to handle some AJAX posting issues. I read a little on it and I see it is a wrapper around Knockout JS. So I wonder what are the real differences between the two? Should I bother with Knockout JS since Knockout MVC exists? When would I use one over the other?

Check answered 23/7, 2012 at 18:10 Comment(0)
R
123

Knockout MVC is the bastard child of WebForms. It routes all viewmodel methods through controller actions, meaning everything that happens has to bounce to the server and back. I cannot understand why anyone would take a framework like knockout, which is intended to be CLIENT SIDE MVVM, and force it to call the server for every function.

In addition, performing those methods on the server means the entire viewmodel needs to be passed to the server, and back to the client, for every function call. This is incredibly wasteful.

Using Knockout MVC means sacrificing all the performance benefits of client-side code for the benefit of not having to write javascript. The same trade-off WebForms made. It is not a good one. It is an antipattern.

If Knockout MVC dies tomorrow, the web will be a better place.

Reneta answered 23/7, 2012 at 18:20 Comment(29)
I "assume" it was written to jump on the KO popularity for folks who are more proficient in C# and ASP.NET (both good technologies that I love too). However, I agree that I cannot see a good reason to use KO MVC over KO. One of the major point of KO is the rich client and low network chat.Marleenmarlen
@JohnPapa I loved C# and ASP (MVC) before I learned Knockout. Not wanting to learn new technologies and new techniques is a poor stance in our industry. Especially when it causes you to adopt techniques that are inefficient. If you want to develop web applications, learning javascript is a MUST!Reneta
hey tyrsius, without turning this into a 'chat', what are your metrics now on knockout vs serverside logic. i've only used knockout to 'preserve' my clientside bindings, haven't done much beyond this. would love to see a few links to demoing richer use between asp.net mvc and clientWozniak
I think that would get chatty. My email is in my profile, feel free to contact me with any questions.Reneta
-1 from me. Whatever you said is correct but there are still other place where I want to work on the model without sending data to the server and back.Pigeonhearted
@Int3ὰ That's my point. Knockout MVC sends the model to the server and back. Knockout does not do that. Why are you downvoting me for the behavior of a framework that I am accurately warning you about?Reneta
@Tyrsius that's one point which I already said you are right. Still there are other nice little features.Pigeonhearted
I think it's important to keep in mind there is an appropriate use that leverages these behaviors. For example, a single page application that has an Add/Edit/Save button, requires a trip to the server. In traditional post you send the form, and get back an entire rendered HTML. With Knockout MVC you only have to render json on the return instead of an entire page. AJAX approach would require you write the JS and Controller code yourself. So in this scenario Knockout saves you duplicate JS, and performs better than traditional. Like anything it can be used or abused.Simulated
@Simulated Yes, but that add/edit/save trip is only going to send the whole viewmodel in the final action. In KnockoutMVC, any action (such as validation, or adding to a typed array) will require the whole viewmodel to be sent. This means every action that Knockout would normally handle on the client, quickly, will be handled by the server, which will be latent. If you don't care about performance, then yes you can write less code. But this is a bad tradeoff to make. If you want to write fast, performant web applications, you will need to write javascript, and you will need to write client code.Reneta
@Tyrsius Yes I agree. That's what I mean by how you leverage it. I'm not sure if there's a way to use knockout, but not use its validation, but instead do validation the old way of writing your own JS. Aside from that, my main point being that you would NOT create functions in knockoutMVC that you would only do client side. Properties are better there because they do become client side JS. I agree it is one of those frameworks that you could easily shoot yourself in the foot with.Simulated
@Simulated Are you recommending having half the viewmodel code on the client, and half on the server (from KnockoutMVC)?Reneta
@Tyrsius No, when you say "viewmodel code", you mean like declare some properties of the view model on the server, and then the other half of the properties on the client? That's not at all what I'm saying.Simulated
@Simulated Ok, so you mean define your models in C# with KnockoutMVC, and then write all the functions in javascript so they run clientside? If not, I really don't understand what code you saying should be done in KMCV.Reneta
@Tyrsius "what code you saying should be done in KMVC*" I gave an example of saving an item. This is something you'd either be doing a regular post or ajax for anyways, so doing it instead as a KMVC function is easier than ajax, and more efficient than regular post. AddNewItem, SaveEditItem, things that in a Single page app, would have normally been an ajax request.Simulated
@Simulated But to do that, you end up defining the model in C#. Then you end up writing all the "client" side code for that model in javascript, so your model code is half and half. I think that's a really bad idea. Especially if you save code needs to use some of that client side model code (like validation, for example), and it can't. You are going to make a bigger mess splitting your VM code between c# and JS than just going pure one or the other. But going pure C# with KMVC means losing all the clientside performance benefits. I don't see any good methods for utilizing KMVC.Reneta
@Tyrsius "going pure C#" I've never seen any framework that let's you go pure C# for client side web code, not counting silverlight. Can you point me to such framework? I wouldn't want to write an app in pure javascript either.Simulated
@Tyrsius For simple validation, you can generate markup that leverages attribute based JS libraries like jquery.validation.unobtrusive, so that you don't have to write any JS for validation. For more complex validation, you HAVE to write javascript, or do without clientside validation. So you get simple validation for free, and complex validation can be pure server-side C# without any client side feedback, and is handled the same way you traditionally would, returning an error message that populates a property mapped to an element. If you want a complex rule client side, it requires JS.Simulated
@Tyrsius What is appealing about KMVC is that you can move towards writing less JS. 1) Property expressions, 2) Functions. My point was functions shouldn't be counted as a bad feature, because if you use them properly, you should only use them in situations where you would have previously done a server request anyhow. They allow you to do the same request, but in less code.Simulated
We should move this to chat.stackoverflow.com/rooms/23257/…Reneta
@Tyrsius, I'm glad I found this page, thanks for this. I was seduced by the promise of an easier development experience, and was considering using KMVC on my current project, but was wary of depending on a 3rd party library without knowing more. Thankfully my caution led me to this page. Your point about the server calls defeating the purpose of Knockout is crucial, and has successfully deterred me from KMVC (with all due respect to the KMVC devs). The fact that John Papa agrees with you is the clincher. I'll go with plain old KO + MVC.Aeciospore
The question asked why use Knockout MVC, not why NOT to use it. If you are developing something for a local LAN where performance doesn't matter it may has advantages for people unfamiliar with knockout like being much easier for them to use.Sexagesimal
No, the question was "is there a reason to use KMVC instead of Knockout" To which my answer was "No." It's also quite common when people ask for reasons to do something to talk about why they might not; there is a sort of relevance to it.Reneta
Brilliant answer. I love C# and I love JavaScript, but why you'd use a server-side framework to compile HTML and Knockout binding expressions is beyond me. Why not just learn and manipulate KO on the client in the first place?Pupiparous
Tyrsius is totally wrong, Maybe you never used the KnockOutMVC to create a complete application. Applications where data manipulation is needed(CREATE,UPDATE,DELETE) need a server side function to work, you can't live without this. The KnockOutMVC create entire model to use on client, handle the connection to server and create the view with bindings for the client usage. All client logic keep in client without server needs, maybe you miss interpreted the right use of it.Hardener
Just to complete my last comment: as AaronLS comments, you can create the model on server and embed to the client model where the functions are, is there no problem and no mess if you always follow this logic, if your model changes, How easy is to change everywhere using JS? With use of KMVC, all logic are consistent. The samples used on their docs are very bad for real projects, but is intended to learning and you should create your own code to take advantage of this library and remove inutile server processing.Hardener
@DiegoMendes Yes, CRUD needs something on the server, but not the entire viewmodel. KMVC puts the entire viewmodel on the server, and anytime properties change it goes to the server to get those changes. In a normal KMVC app only the saved item would go to the server, but in KMVC the entire viewmodel is sent. I am not saying it isn't easier, I am saying it is wasteful and slow.Reneta
@Tyrsius if you use all generated methods created by KMVC the code will return entire viewmodel to server, generally is it what we do when update something on server. Anyway, if you need a special event where only few information must be send to server, you can create by hand, as you usually do on KO. The benefits of KMVC is generation of viewmodel and the view with bindings ready, the rest you do on client.Hardener
Isn't not writing javascript a good reason? though there are other ways to get this result.Plumage
Well thats stopped any chance of me considering it :)Mike
T
21

I just ran across this question which has some pretty negative responses. I'm going to quickly add my two cents worth.

I have only just started using KnockoutJS. Since I'm building ASP.NET MVC apps, it seemed logical to me to use something like Knockout MVC. For the most part, it seems like a great idea. I don't want to be spending time writing javascript and <!-- ko --> comments through my pages if I can do the same using .Net functionality that I know and love.

Having said that... yes, there are limitations to KMVC at the moment. Sending the entire model back to the server is a big one. So what I've done is started my own fork of knockout-mvc. The changes have been necessarily rushed at the moment. But I now have ability to:

  • create sub-contexts (with completely different models or components of the view model)
  • pass selected portions of model back when calling the server
  • expect a different model back from a call than what was sent
  • fire events around the ajax calls
  • support more html5 input types
  • pass anti forgery tokens to the server via headers (for ajax calls)
  • probably more I've forgotten

I'm hoping to get back soon and really clean up what I've done. Hopefully, the author will include these changes in his code. If not, I guess I'll keep my own fork going. Either way, there's light at the end of the tunnel. KMVC might need work as it stands, but I believe the concept was definitely worth doing.

I definitely think

If Knockout MVC dies tomorrow, the web will be a better place.

was a bit harsh.

Edit:

I was looking at the comments and looked again at what the original question was. Having done that I think a little bit more should be added to my answer:

First, the original question was Is there a reason I would use Knockout MVC instead of Knockout JS? To answer/clarify (maybe I'm just being picky) that: Knockout MVC is a framework designed to make it easier to integrate KnockoutJS with your ASP.NET MVC app. It does this mostly by using familiar, strongly-typed constructs to generate KnockoutJS tags. It is not a replacement for KnockoutJS. By all means use KnockoutJS. The question is really whether to use Knockout MVC as well.

Having said that, the choice is still yours as a developer to choose when to use various aspects of all the tools available to you. If you want to handle a certain aspect of functionality by performing a full request back to the server, then do that. If you want to perform an ajax request to retrieve/update data, then do that. If you want to perform functionality purely client-side, then do that.

Using Knockout MVC does not prevent you from utilising KnockoutJS to it's fullest. Using Knockout MVC does not prevent you from writing additional javascript to handle as much client-side functionality as you want. Just because Knockout MVC provides you with a short-cut to generate ajax callbacks to the server does not mean you have to use them. Although, if you application ever persists data, it's going to have to call home at some point.

There are reasons for building an application backend using ASP.NET MVC compared to just using Apache to serve static HTML and script files. Knockout MVC allows you to continue to take advantage of those same benefits to assist with KnockoutJS integration.

Thermodynamics answered 17/9, 2013 at 2:44 Comment(7)
I think I don't want to be spending time writing javascript is the both the reason KMVC exists, and its biggest flaw. You are fighting the web when you try to avoid javascript.Reneta
@Tyrsius, I will have to disagree with you. I'm not trying to avoid javascript. I'm avoiding having to manually write javascript when I can use a tool to do it for me. It's the same reason why I would use KnockoutJS in the first place. I could write that functionality myself, but why when it's all been wrapped up in a nice toolset for me. Likewise, why manually write javascript (the basic bits at least) in my files when I can have KMVC do it for me? There should be no difference to the resulting page, just in development effort.Thermodynamics
Except there is a difference in the resulting page, your answer addresses it: KMVC requires the server to do anything. A regular KnockoutJs app doesn't. That's not just a difference in development effort, that is a difference in performance.Reneta
I think you are assuming a worst-case scenario. If used properly, KMVC should be a tool that assists in the generation of Knockout bindings, etc. The performance benefits are still there. The web application would of course still be dependent on the server to at least perform initial page generation... just as would any web-based application.Thermodynamics
Except they aren't still there. As soon as a viewmodel function goes to the server to perform its logic, as any viewmodel function or computed observable does in KMVC, the performance benefit has been lost. Knockout would have done that clientside, KMVC needs a server request. There is no way around it: KMVC trades performance and responsiveness for not writing javascript.Reneta
My 1 cents worth: not all web apps are deployed to the internet; some are on webservers on intranets; they run over 100mbps wire, so that server-roundtrips are a trivial load.Wastrel
@Nigel Whatling Did you ever get a chance to fork your changes?Brueghel
S
13

I find Tyrsius' answer a bit too negative. Knockout MVC is still in early development, but from what I can see it has some advantages and is less server heavy than Webforms for example. Visiblity dependancies get handles entirely on the client, only when using functions a call is done to the server. When working with complex data structures, it sometimes is required to go via the server anyways, so then Knockout MVC might be a good way to save on writing a lot of Ajax-handling yourself.

It is true it always sends the entire model back and forth, which gives some overhead as opposed to building it yourself. But I wouldn't write it off entirely. Especially when it gets proper client-side handling for complex validations in the future.

Sensuous answered 27/7, 2012 at 9:1 Comment(1)
So the best thing you can say about this framework is that it will be better in the future?Reneta
S
11

I've come across this post after searching a bit about knockout mvc. Although I agree with the waste of network bandwidth, I'm quite seduced by that line of code :

@{
  var ko = Html.CreateKnockoutContext();
 }

This is a neat and clean way for generating the knockout viewmodel. Has anyone used knockout MVC just for that feature and without moving all the logic to the server side ?

Stampede answered 11/3, 2013 at 15:33 Comment(3)
I would love to see an response to this as I find myself repeating a lot of code client side that I already wrote server side.Rhett
@Stampede I have found a way to do this without KnockoutMVC. Just use Knockout Mapping: var myViewModel = ko.mapping.fromJS([Return MVC model as JSON]);. Works w/o AJAX.Allegra
I have stopped using knockout to AngularJS, but thanks for sharing this :)Stampede
P
8

The beauty of Knockout.js is that you can get your application served by simply passing JSON back and forth from the server without having to push an entire view that the server had to chunk away at to generate HTML.

It seems very counter-intuitive to put that back on the server again! If that interests you, you're better off using the razor syntax to accomplish your binding in the first place.

My suggestion would be to use knockout.js to do your binding so that the binding takes place on the client rather than the server if this is the goal you're going for. If you want your view to be data bound on the server, use razor.

Parts answered 23/7, 2012 at 18:21 Comment(8)
+1 as well. the combo og knockout on client with razor serverside seems the 'sensible' way for me. tyrsius's fine sentence, strikes a chord for anyone that's evr had to deal with webforms!!Wozniak
@jimtollan It seems that with KO-JS you have to write your ViewModel twice. One time on client and another on server. That doesn't seem very sensible. It seemed that KO-MVC solved that problem. However, I didn't realize it brought a whole host of problems with it.Check
@dotnetN00b, this is true. The knockout mapping plugin will solve this in some cases, but in others you may need to write your viewmodels twice. The thing is, your c# viewmodels shouldnt have the same functions in them, just he props. Any clientside action will be in your KO viewmodels, and any server action (if any) will be in c#. In exchange for this, you keep fast, performant client-side views, and consistent data.Reneta
@dotnetN00b,not always. I find that in most cases, the ViewModel is only defined in the js, since the controller actions will just send JSON based off the domain model and not a separate view model.Parts
@Parts How are you getting the initial data for the view? If they are anything more complicated than a straight db record model, they will probably get a server-side viewmodel.Reneta
@Tyrsius I've been using KO for SPA's so I'll push a single, and usually pretty bare View. The rest is done by communicating by passing JSON back and forth. For a non-SPA, I'd imagine, you'd have both--My comment was just to let him know that it's not always the case :)Parts
@Parts No, that's a good point. SPA's may not need server-side viewmodels. I've only done one in a project so far, but I still needed a viewmodel for loading non-initial states. Perhaps I could have found another way to do that and avoided the duplication.Reneta
@Tyrsius Well my ViewModels (server side) are just models. I have classes that handle business logic elsewhere (also server side).Check
G
6

More, knockout.js sure is very good at client side data display/delete/insert/update, and client side data calculation. If a real business logic is as simple as that, we must apply knockout.js directly.

The truth is, business logic is not always simple like that. For example, when client insert a new record on view, system possibly need to check User's authentication, set default values for the new created object based on some business logic or formula etc... All this, anyway should go to server side and checking logic based on database data.

Developer is able to translate all required business logic into java script methods inside knockout.js view model. But this way, the design violate the rule of handling business logic centralized.

The maintain will become nightmare for such design.

Summary, what framework choice really depend on business requirement. Sometime, performance is not the first consideration.

Guinevere answered 17/11, 2013 at 22:4 Comment(0)
T
6

I can also see a lot of good use-cases with Knockout MVC library. I could hardly integrate KnockoutJS into our MVC web app, exactly because of reasons which were pointed out by for example @ChinaHelloWorld. Here are some cases where I find it extremely helpful.

  1. Strongly-typed bindings

I liked the nice strongly-typed HTML helpers methods, which became completely useless and messy when it came to setting up KnockoutJS. The best thing I could do is to manually attach my binding attributes with the extra parameter of the helper methods, but I had to use magic strings there again. I like the helpers provided by Knockout MVC for creating inputs and other elements with strongly-typed, C# expression based bindings. However, here I would like to mention that I miss the name attribute of the generated fields, so I needed to tweak it a little.

  1. Strongly-typed binding syntax (kind of)

When using pure string bindings, there is always a good chance of misspelling, or not exactly knowing the correct format of the binding which you'd like to apply. With the fluent API of Knockout MVC and the VS IntelliSense it's really easy to apply the correct bindings.

  1. (Almost) Automatic conversion from computed C# properties to computed bindings

Just with application of the small [Computed] attribute, Knockout MVC can generate the corresponding binding expression in correct KnockoutJS syntax. This one is very useful as well I think.

  1. No viewmodel code duplication

In the classic way, I needed to have the viewmodel class in C# code, and then (nearly) the same viewmodel code in JS (with observables). Well, THAT was frustrating for me, and I got extremely happy when I saw the technique used in Knockout MVC. However, I needed to tweak it a bit for being able to use it with really complex viewmodels (nested viewmodels, collections, etc.), and to be able to extend the mapped Knockout viewmodels with for example any needed custom JS method or computed observable.

So here are at least four very good points. And about viewmodel round-trips: no-one told that anyone of us need to use the server-side processing mechanism of Knockout MVC. I wouldn't use that either, only if there is some complex business logic which really needs to be processed on the server. But in most cases, Knockout MVC is just for simplifying the binding and setup process of MVC Views and KnockoutJS. So I don't quite understand the bad opinions above. I think who wrote these opinions did not take the effort to learn at least the basic concepts of Knockout MVC. Yout definetely should NOT use Knockout MVC instead of KnockoutJS, but besides KnockoutJS. Understanding Javascript and at least the basics of KnockoutJS is still mandatory in any case.

I wish the author continued the development of Knockout MVC, because besides these good points, there are some features and refinement which would really make it even more powerful.

Taitaichung answered 11/12, 2013 at 17:46 Comment(5)
Regarding the point 4: you don't need to duplicate your viewModel if you have a good mapping/merge technique on client side, so, here i only have properties on the Model that i don't need to Set on the server, this way i don't need to create them on both sides.Piaffe
@DavidFreire that's true in less complex applications, but when building a really complex one, at the end of the day I always wished I had those observables declared. For example if I want to create a computed which is based on some other observables then I have to have them declared, can't map them on the fly. Actually I had dropped Knockout MVC in the past year and use my own server-side helpers, and I've created a "tool" to translate my C# models to TypeScript. This technique works really great all together. Once if I have time, I will publicate this tool somewhere.Shrewish
You are completly right, it is a problem if you use computed observables on your view, but for simpler cases it works.Piaffe
@ZoltánTamási did you ever get to publish that tool you have mentioned?Ureter
@Ureter If you mean the C# to TS "converter", I haven't published it and although I still would like to, unfortunately I'm not planning to, because it would be quite a bit of work and I have really limited freetime in these years. I use it as part of our internal framework. There are several similar options on the internet though.Shrewish
G
4

In .Net MVC pattern, view model already marking into each view/partial view clearly with tag "@model yourmodel", which can guide developer to understand what will do in this view.

When using knockout.js MVVM pattern, you possibly would not see any .Net view model, except tags like "data-bind" in the views. This would make the view and controller uncoupled and difficult to track logic specially for a new developer in a team.

I believe knockoutMVC can solve such difficulties and saving a lot of javascript codes which will make the system difficult to maintain and understand.

Since knockoutMVC makes the design still stick on applying server-side view model which is easy to track and maintain since it is the C# code.

For a business project, manager should always focus on easy to develop, easy to maintain, easy to upgrade and easy to understand and quickly delivered to make money.

Sacrifice a little bit of performance but make it simple, consistency at client-side and server-side should be a key point. Javascript is a big maintenance issue.

Does it really a matter sending back the whole view model back to server-side? If it does, we can split a big model to several small models.

Guinevere answered 17/11, 2013 at 18:28 Comment(1)
Brilliant and totally agree based on very bitter experienceMike
L
2

You still have the performance if you are not using functions generated by komvc. As Nigel said, the initial page generation would still have to be server generated. You can always add user scripts and create functions on the client side that won't need to go back to the server. It's a tool that gives the developer a bit of productivity. The comparison with web forms on performance is sure exaggerated. Folks, that's one tool that sure helps you meet your deadline.

Lenoir answered 16/10, 2013 at 17:37 Comment(0)
O
1

I will add my 2 cents in favour of knockoutjs, though it is little complicated to write compared to knockout MVC, the benefit you get is huge when it comes to re-usability. The client code can work harmoniously with other technologies as well.

Keeping aside the security perspective I personally feel knockout js is a way of complicating asp.net MVC and it should be used as is (knockout js) with pure RESTful applications such as asp.net webapi.

Odel answered 27/3, 2014 at 11:58 Comment(3)
What security perspective?Footle
You generally need to send much more information to the client if you are using the client to manage what to hide/show and other functions typically done in knockout examples.Sexagesimal
Security perspective in my context, may be refer this for example: https://mcmap.net/q/276738/-mvc-4-web-api-securityOdel
D
1

Knockout MVC is a powerful extension for ASP .NET MVC that allows you to implement the website client functionality directly on your .NET project using developer friendly fluentAPIs without Javascript and removing a lot of duplicated and repetitive code.
knockout MVC is the same as coding ASP .NET MVC razor and you get the client functionality without any extra hassle.
You won't have to code a view model and lines of binding code.
I have been using koMVC on most of my websites and the develop time reduction, easy maintenance and mininal learning curve are a huge payoff.
I suggest you check their website and have a go with some live examples. http://knockoutmvc.com
It wont take long for you to fall in love with it.

Deal answered 23/11, 2016 at 5:10 Comment(1)
Agreed. At the same time, being that its a wrapper for knockout (not a replacement), you can use it as needed. I wish it was still in development to support the latest version of knockout.Brueghel
N
0

MVC is an architecture pattern which separate into three component, Model, View and Controller.

KnockoutJS work best with the MVC architecture because the framework’s data binding require the use of controller. There are frameworks such as AngularJS which focuses more on the front end and therefore they work better with the MVVM architecture pattern (model, view, view model). Their data binding features also doesn’t require the use of controller which reduce the scope of binding.

Nightly answered 9/2, 2018 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.