Working with non-Umbraco data in MVC and Umbraco project? - umbraco

I am working on a project that has MVC 4 and the Umbraco CMS installed. I apologise - being newbie, my question may be weird.
My question is: how do I work with types which I don't want to manage through Umbraco back office?Rather, it will be simple data coming and being stored in SQL Server.
Specifically I want to ask:
Can I create a controller in MVC and bypass Umbraco?
What controllers should be inherited from? Should they be standard MVC Controller, SurfaceController or RenderMvcController? Again, it will not be an Umbraco document type or data.
Will views be inherited from UmbracoViewPage, UmbracoTemplatePage or it can be a standard MVC view?
How will the URL of these views, controllers and actions change? In Umbraco, the URL depends on the content tree, but how it will be with non Umbraco controllers, views and actions?
Thank you so much for your precious time, guidance, sharing and help; I highly appreciate it.

You are asking a lot of different questions here.
When developing with umbraco Umbraco it's not uncommon to embed external data into your website. If we already tell you that you can use (almost) any type of dataaccess you use in plain .Net projects.
Don't loose your umbraco context
It's important when pulling in external data (e.g.) products, that you don't loose your umbraco context. You still have a breadcrumb to render, css classes for active menu's to set and so on. Your "external data" belongs probably below a node. Therefor it's a bad idea to use Standard MVC controllers.
Dirty razor
Because your views are in razor, you COULD put every extraction of external data into #{ ... } in your view. If you are not an experienced programmer, this works. Although topics about maintainablility and DRY principles are questionable :-)
RenderMvcController versus SurfaceController
When you use a RenderMvcController you basically are are creating a Controller for a specific document type. Each time umbraco is rendering a node of this document type. This controller will be invoked and the model you render is send back to the View. As you might guess, this is one of my favorite places to extract data and push it to the view.
A surface controller on the other hand is a controller for a partial view, extremely well in handeling form postbacks.
Both of these controllers can be used for the front-end of your website, not for the backend.
Inherit your views
You can do with your views what you want. But if you inherit your view from UmbracoViewPage you still have all the #Umbraco.Whatever power available in your views
Your URLS stay the same
Because you "hijack" a route using the RenderMvcController, you can just trust the umbraco backend to go to the right URL. The querystring can be used to get external data you want.
Other controllers or methods
Sometimes, if I can't use the controller above, I create an extentionMethod on the IPublishedContent. Like that I can write code like this:
foreach (var myObj in Model.Content.GetMyExternalData()) {
// do stuff
}
Of if you need to expose data (using a webApi wrapper), try the UmbracoApiController. This REST pure sang.
Data Access in umbraco
You should know that Umbraco uses petapoco as ORM. Therefor you can (and should) consider to use it too. You can reuse the database connection without any problems.
var query = new Sql().Select("*").From("myCustomTable").Where<MyModel>(x => x.Id == id);
return DatabaseContext.Database.Fetch<MyModel>(query).FirstOrDefault();

Related

Umbraco MVC Implementation - View does not depend on Umbraco implementations

I have followed this nice tutorial which explains how you can take even more advantage of using Umbraco as a content delivery system. Tutorial MVC Umbraco => Your model and views should not depend on specific Umbraco implementations which is a huge advantage for real front-end developers.
The controller inherited from Umbraco.Web.Mvc.RenderMvcController in order to access the data from the CMS.
Now my problem is that we can't use #HTML.actionlink for navigation, it seems that this is only supported in SurfaceController.
Now my question is how would we implement navigation inside Umbraco.Web.Mvc.RenderMvcController? Can we still use the native #HTML.actionlink tag?
No you can't. Simply because all requests pass through a single action. In order to retrieve a path to a CMS-managed page, you need to use the node/content traversal the #Model provides. See here for more details on this.
Edit
To clarify, the author of the article is suggesting that the Umbraco implementation should be more in line with a traditional MVC implementation with little or no logic in the views. Therefore, any querying of node data should happen prior to the view (e.g. in the Mappers). So this is where you would have to retrieve the links.
Umbraco's default MVC implementation forces all requests to go via a single action on a single controller. The author's implementation allows the requests to be shared across one controller per document type - which is better IMO. But it still means that things like Html.ActionLink are redundant in the views since there isn't an action per page.
Further edit
If you wanted to build a navigation list with a combination of Umbraco-managed pages and non-Umbraco pages, regardless of the implementation, I would:
Create a child action and view for the navigation in a separate NavigationController that inherits from the SurfaceController
Use the this.CurrentPage property of the inherited SurfaceController to traverse the Umbraco content cache to retrieve the relevant Umbraco-managed pages. You can then use the Url property of each page result to get its path, and the Name property to get the page title
Use this.Url.Action("action", "controller") to retrieve the paths to specific non-Umbraco actions. Alternatively, if the pages are database-managed, use you data layer (e.g. EF, NHibernate, PetaPoco) at this point
Combine these in a Dictionary to make the list you require where the Key is the path and the Value is the page title
Pass this down to the view as the view model.
Of course there any many more things to consider like caching, but in a nutshell, that's a fairly basic implementation.

Razor templates, views and angular.js

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.

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.

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.

What is MVC in Ruby on Rails?

Could someone please explain MVC to me in Ruby on Rails, in layman terms. I am especially interested in understanding the Model in MVC (can't get my head around the model).
Some background, MVC is a (compound) design pattern and was developed in 1979 by Trygve Reenskaug (Smalltalk).
True MVC was primarily planned for use in n-tier (non web) systems and it splits a system into 3 distinct parts, a Model, View and Controller
The Model
Contains data for the application (often linked to a database)
Contains state of the application (e.g. what orders a customer has)
Contains all business logic
Notifies the View of state changes (** not true of ROR, see below)
No knowledge of user interfaces, so it can be reused
The View
Generates the user interface which presents data to the user
Passive, i.e. doesn’t do any processing
Views work is done once the data is displayed to the user.
Many views can access the same model for different reasons
The Controller
Receive events from the outside world (usually through views)
Interact with the model
Displays the appropriate view to the user
** Classic MVC is not suited to web applications, as the model cannot send all changes to the view in an observer fashion (the view is a web page). The Model2 was introduced to overcome the changing infrastructure by JSP team in 90s . MVC Web frameworks are really not MVC, but Model2 (this is true of Ruby on Rails).
Here is a description of GUI patterns including MVC from the master, Martin Fowler
GUI Architectures
The best book I have found so far is Agile Web Development with Rails. It begins by assuming no knowledge, and is quite comprehensive.
Hope this helps to shed some light for you!
MVC basically indicates Model-View-Controller. And MVC used by many languages like PHP, Perl, Python etc. Generally MVC works like this:
Request first comes to the controller, controller finds and appropriate view and interacts with model, model interacts with your database and send the response to controller then controller based on the response give the output parameter to view.
Your Model is the data structure that your program uses.
The View is the part that interacts with the screen or the next level up.
The Controller generally processes data between the model and view
MVC structures are often nested, so a "Model" or "View" may contain its own MVC (Think of a component on the screen. You may just fill it with a string, but behind the scenes the code of the component draws its own little view, has it's own little model (the string you pass in) and has a little controller drawing the data onto the view.
In Rails, the roles of the model, view and controller are well-defined by the framework, any tutorial will point out the three components as it walks you through the files it created.
In other systems, those pieces may be harder to identify. Also, MVC is not "Perfect", just keep in mind that there are valid alternatives, but it's a good way to start organizing.
The Model View Controller principle divides the work of an application into 3 separate but closely cooperative subsystems.
Model (ActiveRecord ):
It maintains the relationship between the objects and the database and handles validation, association, transactions, and more.
This subsystem is implemented in ActiveRecord library, which provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.
View ( ActionView ):
It is a presentation of data in a particular format, triggered by a controller's decision to present the data. They are script-based template systems like JSP, ASP, PHP, and very easy to integrate with AJAX technology.
This subsystem is implemented in ActionView library, which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation. Every Web connection to a Rails application results in the displaying of a view.
Controller ( ActionController ):
The facility within the application that directs traffic, on the one hand, querying the models for specific data, and on the other hand, organizing that data (searching, sorting, messaging it) into a form that fits the needs of a given view.
This subsystem is implemented in ActionController, which is a data broker sitting between ActiveRecord (the database interface) and ActionView (the presentation engine).
Check the links below for clear understanding of mvc in rails:
http://www.bogotobogo.com/RubyOnRails/RubyOnRails_Model_View_Controller_MVC.php
https://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/
I think the best way to wrap your head around MVC is by example. Try coding up a simple Rails app using MVC. There are many tutorials online, such as the blog example at "Getting Started with Rails".
If chose to learn by coding an example, check out the answers to Where can I find clear examples of MVC?
MVC isn't specifically just for Ruby on Rails. It was actually created awhile before Ruby on Rails ever came around. It's mainly just a way of organizing your code so that you have some code that's responsible for your models (the Class version of a database table), some code that's responsible for your views (what's visually being displayed to the user) and code that's responsible for your controllers (what ties the views to the models and performs the bulk of your logic.
That's the non-framework-specific description. Each framework that uses MVC has a different way of implementing it. For Ruby on Rails each model represents a database table as a class that can communicate directly in code with other objects without needing to write any SQL. All the SQL is being taken care of in the background and you just have to think of it as though it were a normal class (well almost, it's not seamless yet). The view is mostly HTML and represents what will be sent to the browser. The controller is just the code that communicates the models and views together.
All in all, MVC isn't specific just to Ruby on Rails...that's just the most popular.
Ruby on Rails does not implement the MVC design pattern. Ruby on Rails has folders called controllers, models, and views. The views folder has HTML files. The controllers and models folder have ruby files. The controllers map to a URL and a method in the controller gets executed upon requesting that URL, the associated view (HTML file) gets loaded and the model (data structure) for it is used to populate the view. Thats the extent of it's likeness to the MVC design pattern. It's a shame that people say it's MVC because it's caused a generation of confusion and misunderstanding of the MVC design pattern.
In Rails, the model is a data structure.
Here's a brief overview at a high level on how the MVC Pattern works:
Controller:
Listens on some kind of interaction/event stream.
Controller can send the model that type of interaction/event.
Controller can also communicate with the the view.
Model:
Models will listen in on the interaction/event from the controller.
Is an abstraction of a data source.
Handles data logic and manipulation.
After it is done with logic, it then sends to controller which will then communicate with the view.
View:
View can communicate with the controller.
Knows how to render data from the Model to the browser visually.
The Controller tells to View to do something with something from the
Model.
A couple of things to note is that models can't communicate with views directly and vise versa. Only the controller can communicate with the view and model, so the controller acts as the delegator for the interaction/event retrieved from users interaction on the browser.
check this link for more clear understanding
one more link to get clear

Resources