Asp.net mvc web application with asp.net web apis - asp.net-mvc

I am new to the Asp.Net MVC. I am doing asp.net web application. I have data layer which I want to be exposed from the MVC Web api only. For web api project i used entity framework as a model and for mvc application i am using entity classes. I am calling the web api from the view with jquery and perform all the operations.
Is that right approach or need to use some jquery framework. Or is there any projects available which uses asp.net web api's only. I warm up google for so many times but didn't find essential. Please assist me here.

You can use jQuery or any javascript framework you please to retrieve data from your API. You could even use raw javascript if you really wanted to. However, if most of your logic is going to live on the client, you'll probably want to look into some MVC/MVVM/MVP javascript library/framework to keep things organized.
A good place to start is the Single Page Application template that is built into Visual Studio 2013 and available for 2012. It uses .NET MVC to load up the HTML markup, styles, and scripts, and then uses Knockout.js to structure the application and send & retrieve data from a Web API controller located in the same app. It's also worth noting that you can grab templates that use other popular javascript frameworks like Ember, Angular, Backbone, Durandal, and more. If you'd prefer one of those frameworks over Knockout then download one of those templates and look through the code.

Without seeing any code, it sounds like you have the right idea. You can use any client side framework of your choice to interact with your Api Controllers (Knockout, Angular, Ember, Backbone) or you can use straight up jQuery.
Since you are new to ASP.NET Mvc, a little clarification on the differences between the traditional Mvc Controller and the new Api Controller seems in order. In traditional MVC the controllers works to select which view (UI) to display married to data (the model):
public ActionResult Index()
{
var theData = serviceLayer.GetData();
return View("Index", theData);
}
You can also return pure JSON data from a controller:
public JsonResult GetMyData()
{
var theData = serviceLayer.GetData();
return new JsonResult()
{
Data = theData
};
}
This had the problem of making it difficult to determine the names of the endpoints that retrieve UI vs the endpoints that retrieve data. The Web Api is Microsoft's implementation of a RESTful framework. Instead of a controller with many different methods (Index(), GetSingle(), GetMany(), List(), DoSomethingElse(), DoAnotherThing(), etc.), the Api controllers usually contain only methods that correspond to the HTTP Verbs: GET, POST, PUT, and DELETE. The same endpoint can then be called differing only by the verb you are using. Take the following endpoint for example:
http://mydomain.com/api/customer/1234
Calling this endpoint will do the following for Customer with id=1234:
GET will return the data
PUT will update the data
DELETE will delete the data
In addition to making it clearer for your own development team, the Api also makes it easier for you to expose your data to third parties. You would need to provide a root URL and a list of your objects and any developer would be able to use it. There are other things you would need to do such as implementing security tokens but I wanted to demonstrate the benefits of using an easily understood framework.

Related

What is the difference between MVC in Angular JS and MVC in ASP.NET or Spring MVC?

I'm trying to understand modern web applications architecture. In ASP.NET MVC, all the business logic classes are in Model and Controller takes and guides user requests.If I am using it, is it possible to use Angular JS which itself is a MVC architecture but all the business logic is in controller and model is just POJO.
Can Angular JS be used only with Web API 2 where it gets data from a RESTful service and it does all manipulation on the client side? Which architecture is most commonly used ?
From my perspective, you're confusing two very different technologies; One is server-side (ASP.NET MVC) an one is Client Side (AngularJS).
The two can certainly be used hand-in-hand as neither are dependent on the other existing. And, IIRC, there is a scaffolding module on NuGet that helps bindings from one to the other (Create JS objects from your ASP.NET POCO objects).
With that being said, there is no reason you need to use both. You can one one or ther other, both, or bring in a different technology altogether (KnockoutJS, etc.)?
In ASP.NET MVC, all the business logic classes are in Model and Controller takes and guides user requests
This is not true. Models (a.k.a. ViewModels) should be plain ("POCO") data containers in ASP.NET MVC. Business logic should come from a layer consumed by the controllers, but in smaller applications or before refactoring, the controller is a more appropriate choice than a (View)Model.
Can Angular JS be used only with Web API 2 where it gets data from a RESTful service and it does all manipulation on the client side? Which architecture is most commonly used?
No, you can use ASP.NET MVC with Angular JS as well by returning JsonResults from controller actions. That said, WebAPI is a better / more appropriate choice. Of course you can also use Angular with many other non-Microsoft tools that return JSON over http(s) (for example node, ruby, java, etc).
To more directly answer your actual question, the main difference between the two is that one is an MVC pattern for the server, and the other is an MVC pattern for the browser. Angular actually likes to call it an "MVW" pattern, where the "W" stands for "Whatever".
Like as other design patterns (Singleton, Factory, Factory method) MVC
is also a design pattern that we can use in any technology like(Java,
.net, PHP) or to any client site scripting. there is no difference between MVC in Angular JS and MVC in ASP.NET and Spring MVc

ASP.NET MVC and Angular JS tipping point

I want to create a largish ASP.NET MVC Web application. On some pages I would like to utilise AngularJS.
This app will not be a SPA.
At what point does this become a problem? For example at what point does running effectively two MVC paradigms become a headache?
Or is it a case of as long as you have clear delineation between what's using ASP.NET MVC (standard action methods etc) and what's using Angular JS then the two run side by side ok without giving you massive code organisation/maintainability headaches?
Cheers for any wisdom.
I'd love John Papas opinion!
Andrew
Since you are only asking for opinions, I will be happy to share my experience. The two do mix very well, and I think in most cases (at least most of my own development) the .NET side becomes very light weight.
Your .NET Web API Controller becomes a simple call to the Data Layer to populate a model or List(Of T) models. This gets returned as JSON to the Angular service.
From there, Angular takes over all of the logic until you need to perform another CRUD operation. Manipulating, validating, etc. all happens client-side in either the model (for me the Angular service acts as the model in MVVM) or the angular controller (which is really a ViewModel).
It's best if you let your model (Angular service) handle as much business logic as possible and restrict the Angular controller to responding to clicks, input controls, etc.
To sum up, let your .NET server side be very light. Just transport data back and forth to the Data Layer. Let Angular do the heavy lifting. You definitely do not need to be building a SPA to see the wonderful benefits of a JS data binding library, of which Angular is arguably the best of breed.
An excellent blog post that contains [ details of what I've discussed here ].
Good luck!
I use ASP.NET MVC alongside AngularJS for a fairly large in-house application. We don't really use many features of ASP.NET MVC beyond the basic page template and script bundling - so everything from the client-side is controlled by AngularJS and client-side routing - except for some distinctions we've made between 'modules' of the app where we wanted a different ng-app for each, along with different script dependencies.
If you're looking to take advantage of AngularJS on a page-by-page basis then I think you have no problem at all. As long as you reference the scripts (both core AngularJS scripts, and your AngularJS scripts for modules, controllers, etc.) correctly then you can just begin decorating elements with ng-app, ng-controller, etc. and it will just work. You could insert the relevant AngularJS scripts for relevant .cshtml pages using a #section declaration.
It will only be more complicated if you need a mix of server-side and client-side routing. Then it will be a case of carefully constructing ASP.NET MVC routes to deliver the SPA functionality where needed.

Create a View against an API controller?

I need to create a website where some of it's pages should be accessible from external clients via an API, but I still want to make regular MVC Razor views to retrieve, display and manipulate the same data.
What's the best way to achieve this?
Update
What the API will have to expose is just data manipulation.
For the web pages, I still want to benefit from the razor chtml views, I prefer not polluting my views with redundant jQ or JS nor data- attributes that consume the data.
Just create an MVC project with the pages you want, and then create ApiControllers (from the Web API framework) to serve as RESTful endpoints. You can program your views to retrieve data from the API actions as JSON objects, and consume them with javascript. Other people can hit the same API actions and use the data in some other way.
If you want to start with a WebApi, and build basic views based on the same data that someone else could access via that API, you could inject your WebApi controllers into your normal MVC controllers, and invoke their methods to get the data that you need to build your ViewModels. This should work all right as long as your API controllers don't need to do anything "outside the box" like inspecting the Request object directly.
A more robust method would be to create a "Manager" layer that handles all the business logic of your application, and then have your ApiControllers be nothing but thin wrappers around calls to their respective Manager classes. This would add a little maintenance cost, but it would adhere to the Single Responsibility Principle a little better.
The easiet way is to use just MVC.
You can also combine MVC + WebAPI in one site.
The reasons to go with the first option is simplicity, and learning maintaining one framework and one set of abstractions.
However if you have any of the following requirements, adding Web API becomes interesting:
1. You want to do content negotiation for response types (say XML vs. Json for the same action).
2. You want to support CORS
3. You want a help page for your API.
4. You want to structure your Url space for your API with rest and resource centric approach (basically GET /resource rather than /resource/GetData).
5. Easier to unit test controllers and actions.
Both frameworks are built by the same team, they both support attribute routing and many similar concepts, and both work well together with one another. I've seen folks take both approaches successfully. Also note that visual studio has templates that combines both of them from the get go.

Should I be using my own Web API

I'm checking out Web API and I'm not sure how asp.net mvc and web api can or should work together.
I want to implement Backbone on the client side, but I'm not sure if I should implement an ApiController or a normal Controller on the server side?
The way I'm doing things (Getting current user / account information) is that a base ApiController will have some of the same functionality as a base Controller would, which would lead to a bit of duplicate functionality, but not sure what would be the other trade offs.
Or would you only create an ApiController for a public service that you want to provide and stick to Controllers for the web app?
If you're planning an API, use the ApiController. If you're doing Web UI stuff, use the classic Controller. That's what both are made for.
This is almost exactly the situation I am in, except that I am using Knockout.js rather than Backbone. I have views for Create and Edit and within each view, a very complex Knockout.js UI which does loads of Ajaxing of JSON back and forth to the server.
Under MVC3 I was using numerous JsonResult methods within the same controller which rendered the views. I've been experimenting with the RC of MVC4 and was pondering whether to go down the "route" (ho ho) of using an API controller for the Ajax requests. I like the strongly typed HTTP classes and the fact that JSON.NET is more integrated, but at this stage, I have to say that the end result of having a separate API controller for my own internal use just didn't feel right. Like you, I found that I ended up with a lot of duplication around security, and the separation of what was related logic simply by content type made things more confusing rather than cleaner.
So at this point (although I have been known to be fickle) I plan to keep using standard MVC controllers for my current context, but I'll jump at a chance to use the shiny new Web API if I end up exposing a public API.

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/

Resources