Razor templates, views and angular.js - asp.net-mvc

TL;DR
What are the best practices when using .NET Razor views and AngularJS?
Context
We are developing a public website (not an intranet application) using mvc4 with razor, and we weren't very familiar with client script, so we started with what we knew: jQuery.
But now things are getting more complicated and we'd like to switch to AngularJS.
On the .NET part, we use Razor templates and UIHintAttribute (plus some custom ones) to render the right html "control". We also add custom html attributes to give extra information to the jQuery part (like title for a tooltip....)
So we already use a declarative way of setting the user interface behavior, that's why AngularJS seems a good option.
Questions
Since we already have models defined server side, and since AngularJS also uses models, wouldn't it force us to duplicate code?
How do we deal with data binding feature, since we already do some binding server side (in the views). Should we make a completely asynchronous application, making AJAX calls from AngularJS to load data, or can we mix both?
Anything else we should be aware of when trying to use both of these technologies?
I did some research on Google, but I can't find detailed ways of mixing Razor views and templates with AngularJS... Perhaps that's just not a good thing to do?

We dealt with this issue for months when working with MVC plus another JavaScript framework (Knockout). Ultimately, if you're going to be using a client-side MV* framework for rendering your user interface, you will find that mostly ditching Razor is going to be your best bet.
Most of the major MV* JavaScript frameworks, including AngularJS, assume you will be maintaining UI state and rendering your user interface based on JavaScript models or view models. Trying to mix in server-side rendering is just not going to work very well.
That's not to say there is no use for MVC when it comes to developing an Angular application. You can still take advantage of some great features like ASP.NET Bundling and Minification. And sometimes it works really well to embed JSON directly into the page using a Razor view or partial as opposed to making an additional AJAX call.
As for models, you may want to take a look at Breeze.js. It's a JavaScript library for data access that goes great with ASP.NET on the server side to share model metadata.

We wrote our own data binding mechanism that synchronizes the angular.js model with a view model on the server side. The javascript model is generated from a JSON serialization of the server-side view model to avoid the duplicate code that you were talking about.
We are using SignalR to update the client's view model from the server.
Server-side changes of the C# view model properties are sent to the client as a packet containing the path to the property, e.g. Persons[42].Address.City, and the value itself, e.g. New York. The view model inherits a base class that takes care of generating the property path, so the actual view model looks quite clean and we can concentrate on business logic.
Client-side changes of the javascript view model properties are sent to the server in the same way. To catch the change events, we encapsulate all fields of the original javascript model in get/set properties where the setter sends the update packet to the server.
Server-side methods of the view model can be invoked in a similar way. All objects in the view model have an invokeMethod function that can be used like this: Products[42].Manufacturer.invokeMethod('SendEmail', 'mailsubject', 'mailbody'). This will send a packet to the server containing the method path Products[42].Manufacturer.SendEmail and the arguments as an array of ['mailsubject','mailbody'].
In conclusion, the html view (kind of) binds to the view model on the server side where other systems, such as regular Razor views can work on the same objects.
The source code can be found here: SharpAngie.

Related

What role does MVVM play in ASP.NET MVC 4 web applications?

While I'm reading the book "ASP.NET MVC 4" I'm wondering about MVVM. I started googling and cannot find any books about developing web applications using MVVM, so I must be missing a bit of information here.
From what I understand, MVVM is used in web applications on the client side via knockout.js and other frameworks.
If however I was to develop a Windows Phone application, I could use MVVM directly without using MVC.
Does that mean, the concept of MVVM / data binding just does not apply to client-server web applications?
MVVM is really sort of a subpattern. There's not really any "MVVM" web app frameworks out there. They're all MVC and you pretty much just incorporate a view model if you want one.
With ASP.NET MVC, in particular, you just create a class, generally with a name in the form of [Model Name]ViewModel or [Model Name]VM. That class will have only the properties from your model that you'll need to work with and anything extra that doesn't make sense to put on your actual database-backed model, like SelectLists, etc.
In your action, you just pass an instance of this view model to your view instead of your model:
return View(viewModelInstance);
And, of course, make sure your view accepts that:
#model Namespace.To.MyViewModel
The only slightly complicated part is wiring the view model to the model (i.e., getting data to/from the view model/model. You can do this manually by explicitly mapping the properties, or you can use something like AutoMapper.
MVVM is the standard design pattern for WPF/Silverlight development, and should not be confused with MVC for ASP.Net development.
The two may sound similar and share some common parts, but they are two different design patterns.
From what I learned about knockout.js, it was designed to create "data bindings" similar to what you would use in WPF/Silverlight development, which is why the MVVM design pattern applies there.
To quote from another answer of mine regarding the differences between MVVM and MVC
In MVVM, your code classes (ViewModels) are your application, while your Views are just a pretty user-friendly interface that sits on top of the application code and allows users to interact with it. This means the ViewModels have a huge job, because they are your application, and are responsible for everything from application flow to business logic.
With MVC, your Views are your application, while your Controller handles application flow. Application logic is typically found in ViewModels, which are considered part of the M in MVC (sidenote: the M in MVC cannot be considered the same as the M in MVVM because MVC's M layer contains more functionality than MVVM's M layer). A user is given a screen (View), they interact with it then submit something to the Controller, and the Controller decides who does what with the data and returns a new View to the user.
MVC is a one-way data-binding system.
Fill your Model in Controller, then pass it to View.
MVVM is a two-way data-binding one.
Fill your Model, use it in View, when the View state's changes, your Model update automatically.(Vice-versa)
Does that mean, the concept of MVVM / data binding just does not apply to client-server web applications?
No, you can apply the MVVM pattern to client-server web applications.
In fact Asp.Net MVC actually kind of does use this pattern - when the controller creates the view, it can pass in a "view-model". This view-model is often a POCO data object with all the data that a particular view needs, drawn from the model (database). The view uses this data to render the html page.
MVVM on wikipedia says it was introduced by Microsoft with WPF. Specifically, the view binds to properties on the view-model. The view-model then maps this to the database. By this definition then, Asp.Net does not exactly match that. Client-side frameworks like knockout.js and vue.js do support this kind of 2-way binding with view-model properties.
All these patterns are based on the fantastic MV* pattern. It was originally called the MVC design pattern. So this is the exact same pattern as Asp.Net MVC then? Actually, not quite. Controller means something completely different to start with (see MVC on wikipedia). The original MVC controller handles all user input directly not via the view. Second, the original MVC pattern was designed for a desktop app GUI and Asp.Net MVC adapted the pattern for use in a client-server web app. An ASP.Net controller is a collection of http end-points which the client-side html page can hit (eg form-post, page-navigation, ajax).
So there are a lot of M-something-V patterns and the general pattern is often called the MVC design pattern.
There's one more important wrinkle: client-side vs server-side. We've introduced rich client-side javascript frameworks and the fantastic MV* pattern is great here too. So now we could have something like: client-side View-Model-ServerHTTPEndPoints and server-side ServerHTTPEndPoints-ServerModel. The server-endpoints refers to Asp.Net controllers or the equivalent in whatever web framework or programming language you are using. From the server-side point of view, the entire client-side html is the view. The client-side model talks to the server ajax api (http endpoints) to sync data or trigger advanced actions. The ServerModel is normally a database. In knockout/vue, instead of client-side "Model", it would be ViewModel. If you use react/vue with redux/flux then the client-side would be View-ViewModel-Model-ServerHTTPEndPoints where the Model would be the redux/flux Stores. Also, often on the server-side, a service is introduced: ServerHTTPEndPoints-Service-Model. This way unit tests can hit the service directly rather than firing up the entire web server and making HTTP connections.
I have used MVVM in desktop applications and I have a property in my viewmodels named Model where I store a business object as the model. My views have a property named DataContext where the viewmodels are stored before the views are loaded. A view bind its controls to the business object using the path DataContext.Model.BusObjPropertyName. I have a UserInteractionService that register from the start the relationships between views and viewmodels. When a viewmodel needs to show another viewmodel, it calls the method ShowView in the UserInteractionService and pass the viewmodel as parameter. Then the service instantiate the view corresponding to the viewmodel received, set its DataContext property with the viewmodel and show it.
If it is possible to do the bindings to a path like that above in Asp, all this model can be reused either in desktop as in Web applications.

Web API - Rendering Razor view by default?

How do I get Web API to render a Razor view using the model that it returns? And only XML/JSON when the accept headers (or .extension) is set? Is this even possible?
It seems crazy to require one set of controllers for rendering HTML and another for JSON/XML if they're working on the same models.
Update Darrel Miller has already written a ViewEngineFormatter for Razor which might do the trick, though haven't tried it yet.
I asked a similar question about this in the past on StackOverflow, because I wanted to do the same thing. However, I eventually ended up with an "Api" area and set of controllers, and a standard set of MVC controllers for the website.
In hindsight this actually wasn't a bad thing. I've found I tend to do different things in each set of controllers anyway. My views aren't just CRUD but tend to contain extra contextual data, so returning view models specific to that page is nice.
I think if I had stuck to my goal of combining the two I might have ended up with either over-complicated controllers or a user experience that wasn't as optimal as it could have been. So while this isn't a direct answer to your question, in my experience not being able to do this might not be such a bad thing.
Instead I've ended up with a rich set of builders and commands that most of my controllers delegate to. That way I can reuse most of the controller logic while being able to do specific things for API versus the web:
http://www.paulstovell.com/clean-aspnet-mvc-controllers
Yes, it is how it is designed for: Web API for data and MVC for rendered views. I know that some people will try adding view engine support to web API but it is not designed for it.
My personal view on this is that this parallel world between MVC and Web API (which is the source of most criticisms while community has generally praised the product) is mainly a consequence of the fact that Web API has been added to MVC without having a reference (or knowledge of it).
As Jon Galloway said on a recent podcast, had the team have HTTP knowledge they have now (as well as hindesight of the popularity of REST API now which they did not have then), they would have designed just a single pipeline serving data and rendered view alike.
I can only speculate that the future version of MVC/Web API will be presented as a single pipeline. In fact, this parallel world might have been a careful plan to unify them in the near future.
It seems crazy to require one set of controllers for rendering HTML
and another for JSON/XML if they're working on the same models.
AFAIK, that's how it is. Standard controllers should be used for rendering HTML and ApiControllers for JSON/XML.
It seems crazy to require one set of controllers for rendering HTML
and another for JSON/XML if they're working on the same models.
Web API is exactly what it is called - a technology for creating API's.
If you are creating an ASP.NET MVC application and want to return some JSON for your own purpose then you don't need content negotiation etc. therefore you don't need Web API (just use plain old good JsonResult).
If you want to create a reusable API than Web API is what you need but your client application should consume it in the same way as everybody else.
Web API isn't meant to be a "hammer" for "nailing" all non-HTML requests - use it when you need it.
I am looking for something similar to this, but not entirely. Through scouring the web, I found a couple posts by Fredrik Normen. He writes about this exact problem space and actually identifies a third-party solution in the second post listed. Basically, the solution involves creating a custom MediaTypeFormatter that knows how to handle views using the Razor engine provided by Microsoft (through the use of a third-party library).
Using Razor engine together with Asp.Net Web API to create a
Hypermedia API
Using Razor together with ASP.NET Web API
ASP.Net Web API and using Razor the next step
Hopefully Microsoft will implement something soon in Web API as Hypermedia seems to be gaining traction.
Hope this helps!

ASP.NET MVC with Knockout and Web API: does it make sense?

does it make sense to use KnockoutJS Viewmodels in combination with ASP.NET MVC3 or 4? Because it is not very DRY, isn't it? I have to write models for EF, Viewmodels for the MVC Views and Viewmodels for Knockout... and i lose a lot of magic. Automatic client-side validations for example.
Does it make sense to use MVC at all if one sticks with the MVVM Pattern?
With Knockout Mapping, you can automatically generate a KO view model from your MVC view model.
This is a proper pattern: your models are raw entities, your data. Your views are the UI. And your view models are your models adapted to that specific view.
This may be an unpopular answer, but I don't use ko.mapping to translate my C# POCOs into JS viewmodels. Two reasons, really.
The first is a lack of control. ko.mapping will turn everything into an observable if you let it. This can result in a lot of overhead for fields that just don't need to be observable.
Second reason is about extensibility. Sure, ko.mapping may translate my C# POCOS into JS objects with observable properties. That's fine until the point you want a JS method, which at some point, you invariably will.
In a previous project, I was actually adding extra methods to ko.mapped objects programmatically. At that point, I questioned whether ko.mapping was really creating more problems than it solves.
I take on board your DRY concerns, but then, I have different domain-focused versions of my POCOs anyway. For example a MyProject.Users.User object served up by a UserController might be very different from a MyProject.Articles.User. The user in the Users namespace might contain a lot of stuff that is related to user administration. The User object in the Articles namespace might just be a simple lookup to indicate the author of an article. I don't see this approach as a violation of the DRY principle; rather a means of looking at the same concept in two different ways.
It's more upfront work, but it means I have problem-specific representations of User that do not pollute each others' implementations.
And so it is with Javascript view models. They are not C# POCOs. They're a specific take on a concept suited to a specific purpose; holding and operating on client side data. While ko.mapping will initially give you what seems to be a productivity boost, I think it is better to hand-craft specific view-models designed for the client.
btw, I use exactly the same MVC3/KnockoutJS strategy as yourself.
We use knockout Mapping to generate the KO view models well.
We have a business layer in a separate project that does CRUD, reporting, caching, and some extra "business logic". We aren't going to be using EF, or something similar. Currently we've defined c# classes as MVC models, and our controllers call the business layer to construct the Models that are defined in the usual place in our MVC app. These C# models get serialized as JSON for use in our pages.
Since everything we do in the browser is c#/JSON based using knockout, we aren't using MVC models in the traditional MVC way - everything gets posted as JSON and serialized to c#, so we don't use MVC model binding, validation, etc. We're considering moving these models to our business layer so they can be tested independently of the web app.
Se we'll be left with an MVC app that has controllers and views, but no models - controllers will get models that are defined in the business layer. We're nervous about departing from the normal MVC structure, but a KO/javascript based client is fundamentally different from a DOM based client that MVC was originally built around.
Does this sound like a viable way to go?
I work now on project which mixes MVC3 and knockouts and I have to tell you - it's a mess...
IMO it's nonsense to force some patterns just to be up to date with trend.
This is an old topic, but now in 2014 (unfortunately) I still feel this question has a huge relevance.
I'm currently working on a project which mixes MVC4 with knockoutjs. I had some difficoulties to find whichs part should be handled on which side. Also, we needed a "SPA-ish" kind of architecture, where each module has its own page, but then inside that module there is only AJAX interaction. Also faced some heavy validation scenarios, and needed to provide user (and SEO) friendly URLs inside each module. I ended up with the following concept, which seems to be working well:
Basic MVC and .NET side roles:
Handling authentication and other security stuff.
Implementing the Web API interface for the client-side calls (setting up viewmodels, retrieving and mapping data from the domain, etc.)
Generating knockout viewmodels from my (pre-existing) C# viewmodels with T4 templates, also including knockout validation plugin extensions from .NET validation attributes. (This was inspired by this aticle). The generated viewmodels are easily extensible, and the generation can be finetuned with several "data annotation"-like custom or built-in attributes (such as DefaultValue, Browsable, DataType, DisplayFormat, etc.). This way the DRY doesn't get violated (too much).
Providing strongly typed, but data-independent partial view templates for each submodule (each knockout viewmodel). Because property names on C# viewmodels are same as in KO models, I can benefit from the strongly typed helpers specifically written for KO bindings, etc.
Providing the main view for each module similarly to previous point.
Bundling and minification of all scripts and stylesheets.
Basic client-side roles:
Loading the initial state of all viewmodels encapsulated into one module page, taking the whole URL into account with a simple route parser implementation.
Handling history with history.js
Data-binding, user interaction handling.
Posting relevant parts of viewmodels to the server, and processing the returned data (usually updating some viewmodel with it).
I hope this could help anyone else who feels lost in the world of trendy technologies. Please, if anyone has any thought on this, feel free to post any question or suggestion in the comments.

wcf and knockout.js combine

I got my datalayer, business layer ready. Now i want to to implement service layer.
I do not want to implement this layer in wcf ria services. Is there any other way to implement this layer in such a way using wcf, so that I get my model through wcf using js.
For example I have my domain 'Person'. (In domain project). Then in my 'PersonRespository' has
InsertPerson, GetPerson etc. to get and store the 'Person' in database.
Now I want to use asp.net mvc to show the person detais.
So next two layer will be Presentation Layer and service layer and manipulate data on client side using knockout.js and I am stuck on following issues.
Where will be mine Presentation layer will live. I am using asp.net mvc so It should be in model folder of mvc application, Is it wise to copy the same code class (Person) to model folder as well from domain model. Event when they are same.
How I will be able to get 'Person' model class in javascript and able to update it from javascript to database as well.
Is my architecture style is of enterprise level or i am missing something.
Any point to tutorial will be helpful.
If you have any further questions please let me know.
Thanks,
Daljit
Question 1:
No you should not be repeating your code. There is talk about this in the DRY (http://en.wikipedia.org/wiki/Don%27t_repeat_yourself) principals of development.
Question 2:
It is recommended that you serialize your model using a json serializer and send it to your UI. It will be updated etc, and then sent back to the services. Google MVVM pattern in javascript to see how this is done. KnockoutJs is a great start in achieving what you want. Its probably best to check out some examples done in knockoutjs to see what is going on. There are also many examples in MVVM for WPF that might help understanding the pattern at a higher level. I would recommend seeing codeproject.com for indepth MVVM examples.
As far as your layers go, you have many options, but a generic recommendation would be:
1) Presentation must be triggered through MVVM bindings, ie if the binding updates, the UI will then update itself.
2) the asp.net side of things should only update the models when sending updates via ajax to the UI. (not everything needs to be sent via ajax, im not saying that. When it does, it shouldn't also send extra html or js to put in the page).
3) Your models should really come from asp.net to the html page. (this will make things easier later, as the page will only be updated via asp.net models and you won't get items coming from multiple domains, which ends up being a nuisance.
4) Your asp.net site should provide a wrapper for your WCF service, and can foward calls to WCF.
OR
If you didn't want to wrap WCF with asp.net and needed your UI to communicate directly via ajax to WCF (should be a rarer usecase like doing an igoogle like page with widgets, or maybe mobile development with no asp.net interaction, ie full js app) Then you can investigate CORS as an option to go from JS to WCF and JS to asp.net (This is of a hard difficulty, easy to program, hard to get working for WCF as there is very very low documentation on it for in my case non IIS hosted WCF). See this page for information: http://enable-cors.org/

MVVM ViewModel vs. MVC ViewModel

ViewModel is a term that is used in both MVVM (Model-View-ViewModel) and the recommended implementation for ASP.NET MVC. Researching "ViewModel" can be confusing given that each pattern uses the same term.
What are the main differences between the MVC ViewModel and MVVM ViewModel? For example, I believe the MVVM ViewModel is more rich, given the lack of a Controller. Is this true?
A rather challenging question to answer succinctly, but I'll attempt it. (Bear in mind that the answers to these kinds of questions are still the subject of debate amongst developers.)
In MVC, the ViewModel provides all the information necessary for a View to be rendered. The data it contains is created using data defined in the Model. The View reads the ViewModel and renders the output. Input from the View is passed to the Controller, which manipulates the Model, constructs an appropriate ViewModel, and passes this to the View for rendering.
In MVVM, the ViewModel serves the same function as it does in MVC, but it also replaces part of the MVC Controller by providing commands which allow the View to manipulate the Model. WPF databinding manages the updating of the View according to changes in the ViewModel (and this effectively replaces the remaining function of the MVC Controller).
It's been a while since I played UI Design Patterns Bingo.. however let me take a stab at this..
MVVM is just something that MS has come up with... because it helps you to get the most out of WPF. You combine the state and behavior of the view into a class (a presentation model) that is easily testable + then you use data-binding to get the data into any view.
This link has a brief of the evolution of MVVM. Combine this with Fowler's "GUI Architectures" series, and you should be on your way.
Update: Didn't know there was something called MVC-VM. Apparently a brainchild of the ASP.NET MVC crowd. Looks and sounds similar to MVVM (except tuned for ASP.NET MVC); the only difference is that it places a restriction that there is 1:1 mapping between VM and View. I'd have guessed 1:N, but everything else matches.
I know this is a (way) old question, but I've been pointed to it as an example of using "View Model" in the context of MVC. I argue that this is incorrect and can lead to confusion by people who are new to either/or/both patterns. Whoever is doing it--stahp. Here's why (and it's even an answer to the original question in a roundabout way).
An example of when this happens can be seen in this question. The user is trying to use a View Model that implements INotifyPropertyChanged in an ASP.NET MVC application, thus mashing together desktop and stateless web application design in an architectural fail and heartbreak.
To put it simply, there is no "View Model" in the MVC pattern. There is, however, a functional equivalent, and that's the Controller. Just to be clear about the parts and their purpouses,
MVVM (desktop applications):
Model - Strongly typed object that holds data to be passed between the View and View Model
View - The UI viewed by the user and through which the user interacts with the system
View Model - Interprets user actions (e.g., via ICommand), performs them, updates application state
MVC (web applications):
Model - Strongly typed* object that holds data to be passed between the View and View Model
View - A UI generator that combines the Model, code and HTML to render a webpage
Controller - Accepts user requests, interprets them, updates application state and uses a View to convert this state into an HTML webpage
The Model is practically the same in both patterns. Desktop models may implement update event notifications, web Models may be dynamic (i.e., not strongly typed), and both may or may not include validation methods or metadata.
The View in the desktop is what the user sees. In the web, it is a generator that outputs HTML for browsers to display on the client side. It must interpret user interaction on the desktop, but on the web that is handled by client side javascript, the browser, and the requests that are sent back to the server.
The View Model/Controller are roughly functionally equivalent, but differ greatly in how they are implemented and how they operate. In the View Model, user interaction with the application is transferred to View Models via ICommands, routed events, and other methods (many MVVM frameworks provide different ways to hook View Models to the UI and other parts of the application). In a Controller, a request comes in with all information needed for the Controller to return a result to the user (assuming it's a 200 OK request). The Controller must perform whatever work is necessary to create the state (aka Model) needed for the HTML generator (the View) to create the response. Design-wise, the Controller sits above the View and Model knowing and controlling both, whereas the ViewModel sits next to the View, passing the Model (and other information) between them.
What really seems to confuse some people is that there are client side MVVM frameworks that you can mix into your MVC application. These exist solely in javascript in the user's browser, and have nothing to do with whatever particular pattern you're following on the server side. You can run a classic ASP website that uses MVVM on the client side. Hell, you can run static HTML pages that use MVVM on the client side. They are that separate.
These javascript MVVM frameworks typically follow a similar pattern to the desktop MVVM pattern described above, but adjusted to work more in tune with the nature of the HTML DOM and javascript. For example, there is no extensive binding system woven into the DOM, and javascript has a very limited type system, so matching up templates to models is much different than in WPF. They also typically work disconnected from the server, and when they need to interact, prefer AJAX calls rather than POSTing the page back to the Controller (AJAX calls typically are handled by WebAPI Controllers in ASP.NET MVC).
So, to summarize, there really isn't a View Model in MVC. The Controller is the rough equivalent, but is very different in how it receives user input, interprets it, and returns a result to the user. Using the term "View Model" to refer to anything in MVC can only lead to confusion, and therefore should be avoided. Use the proper terms for the proper parts of the pattern. It may seem pedantic, but it should help keep things clear and be less confusing to people who are new to both patterns.

Resources