Use of Models in asp.net MVC for API integration - asp.net-mvc

I am using 3rd party API to get and manipulate data used for my asp.net mvc application. Since I am beginner in MVC, from my standpoint I believe that use of models component of MVC pattern in such cases is not really needed. Only need to use models in this case would be if I would like to additionally manipulate data pulled from API.
Could someone please clarify if I am missing sometime in my theory.

I'm with you on your theory. It might seem a bit overkill to create a set of classes when retrieving data form a 3rd party application. In the beginning it may seem like a lot of unnecessary work.
However, my personal opinion is to always map classes in the MVC application. My reason for doing this is to keep as clear as possible separation of concern in my applications. If you need a similar application in the future or you are changing back-end for some reason, the MVC/front-end application will be as independent as possible.
It is also nice to keep a clear separation of concern if you are working with other developers and if the application will be used for an extended period of time. Also imagine if you would like to do some manipulation of the data, like you say in your own words.
To summarise, I think it is good practice to always keep a model class in your MVC application.

Related

Why does HotTowel include Breeze?

This may sound like a dumb question on the surface, but why does the Hot Towel SPA Template include Breeze at all?
I've been spending the last few days learning Hot Towel and its dependencies, and as far as I can tell, nothing in the template actually uses Breeze. Perhaps that is going to change with some future release?
Sure, Breeze is a good library. But it's bound to CRUD methodology and requires you design your ApiControllers a particular way. (Metadata, SaveChanges, etc.) see here
It also guides you to Entity Framework. While this is more of a soft-dependency, since Breeze also shows a sample without it, it still guides you down a similar pattern of implementation using a modified repository pattern.
If you are using a NoSQL datastore, or CQRS patterns instead of CRUD, then Breeze becomes very difficult to use. There are alternative libraries for data access that work well in this style, such as AmplifyJS.
But the rest of Hot Towel is excellent! I especially like Durandal. So the question begs, if the template isn't actually doing any data access - why include any data access component at all? It would be better to ship it without Breeze, and if the end-user wants to use Breeze, or Amplify, or whatever - then so be it. The rest of Hot Towel would continue to shine as a great SPA implementation.
Matt - Good question. Since I created it I guess I should answer :)
When I built the template I had a focus on providing enough to get folks going with the right tools, and just enough starter code to guide the way. I did not want anyone ripping out code. I'm not a fan of templates that start you down a path and make you remove tons of files and code and change direction. Those are samples.
Samples are good. In fact, samples can be excellent (like the other templates, which I feel are more like samples). Those serve another purpose: to show how you can do things.
Back to the Hot Towel template ...if I include code that uses Breeze, I would be tempted to add a datacontext.js and a model.js on the client. They would contain data access code and code to extend the models on the client. Then I would be tempted to add a controller, some server side models, an ORM and a database. Once there, I'd want to use the data in multiple screens, which leads me to more Knockout and caching with Breeze. Then I might be tempted to add editing, which would lead to change tracking. Soon I have a full blown app. Or more conservatively, I have a sample again. While these approaches would provide more guidance on how to put these together, they would not help you "get started" with a template where you can just start building and adding your own code. If I stop short of some of these features, it's still walking down a road that requires you to change how I did it.
As it stands today, HotTowel is pretty darn close to a template in the truest sense. You create a new project and you are off and adding your own code.
You could argue (and you may be) that Breeze shouldn't be in there since I don't use it in the template. Nor do I use moment.js, BTW. However, I argue that they are both excellent libraries that I would not want to build a CRUD based SPA without them. Breeze is flexible, as you suggest, so you don't have to walk a specific path.
The best way to understand the value of Breeze is to build an app that has its features but without Breeze. Then you can see how much code that takes and how involved it is. For one such example, see my intermediate level SPA course at Pluralsight where I do exactly this: http://jpapa.me/spaps
So you ask "why Breeze?" ... because I strongly recommend it for building a SPA.
Thanks for asking and good luck !
Thanks for asking the question.
John, as author of HT, has offered an answer. I, as a principal of the Breeze project, am inclined to agree with him :)
HotTowel generates a foundation for you to build upon. It is not the building itself.
It is a foundation intended for a specific kind of application, a CRUD application based on a specific set of cooperating JavaScript and ASP.NET technologies. Breeze is a contributor ... but not the only one. Knockout, with its MVVM design and 2-way data binding, is particularly well-suited to the data-entry tasks typical of CRUD apps.
Of course there are other kinds of SPAs. There's an important class of apps that mostly present information and accept little user input. Such apps don't benefit as much from data binding and the people who write them can get pretty hostile about data binding in general and KO in particular.
My point is that HT targets a particular class of application ... one that happens to be immensely successful at least when measured by sustained popularity. It delivers the goods for people who build those apps. It may not be the right starting place for other kinds of apps.
It is true that the easy road to Breeze runs through Web API, EF, and a relational database. Take those away, and you may writing more code on the server (and a little more on the client). That may be the perfect trade-off for you.
The authors of Breeze would like to make that path easier. I don't think BreezeJS makes it harder. I don't understand your statement "Breeze becomes very difficult to use." Have you tried it?
Your client can communicate with any HTTP resource in any manner you chose. It is pretty easy to use existing Web API controllers (albeit easier with Breeze Web API controllers). You can use amplify.js if you prefer (btw, you can tell Breeze to make AJAX calls with amplify). You don't even have to use the Breeze EntityManager to query and save data if you don't want to.
The rest of BreezeJS may still have value for you. There remains plenty of work to do after you've figured out how you'll retrieve and store data and whether you prefer Entity-ChangeSet style or Command/Query style.
You'll have to find answers to these questions:
How will you shape the raw JSON data into bindable objects?
How will you hold on to these objects and share them across multiple screens without making redundant round-trips to the server?
How will you navigate from one object to a related object as you do when binding an Address to a combobox of StatesAndProvinces?
How will you track changes?
How will you validate them?
How will you store some or all of the data in local storage when the app "tombstones"?
Breeze can help with these chores even if you don't want it to query and save for you.
And if you're answer remains "I'll do all of that myself, thank you" ... well, removing Breeze from your HotTowel project is as easy as:
Uninstall-Package breeze.webapi

Is it a good practice to use an MVC application's own Web API for Ajax bindings?

I'm writting an application that has many Ajax widgets (Kendo-UI to be percise). It's starting to get messy to have all those Ajax responses without the standard controllers so I was starting to consider making each entities their own controller. If I'm taking the time to do this, I figured I might as well go foward and do those as WebAPIs since I was planning to do this in a not so close future, but hey, it would be done already...
So my question is: Is it a good practice to use an MVC application's own Web API as a Ajax Widget feeds or is there any reason to stick with standard Controllers?
I've seen some arguments about performance, but I don't think this applies to this situation. I believe it was more of a "Controller calling WebAPI" situation which has obvious performance hits. But since it's already a client side Ajax call, weither it goes into a standard MVC Controller or a WebAPI controller shouldn't change a thing, would it?
Edit
Additional information regarding the project:
I am using Entity Framework for the data access.
I have a repository pattern going on with UnitOfWork.
I am using proper a MVC structure (EF POCOs AutoMapped to DTO POCOs in the repository and fed into View Models by the controllers)
This is a MVC 4 project on .NET 4.0
There is a lot of database relationships (specially for the object I'm working with at the moment)
I don't know about "good practice", but it's certainly not "bad practice". I see no difference whether you do it in the app or a different one.
I think its a good thing but only if what you are doing in the API is kept as generic as possible to other applications and services can reuse the API.
Both the applications I have written and continue to maintain use pretty much the exact same stack as your app.
I have recently re-factored one of the applications to use the API for all the common things like lists that I'm binding to Kendo ComboBoxes etc. in my views. Its a fairly large application that re-uses a lot of the same lists such as states, priorities, complexities across various Entities and views so it makes sense to put those in the API.
I haven't gone as far as going the whole hog through. I draw the line with things like this:
public ActionResult GetAjaxProjectsList([DataSourceRequest]DataSourceRequest request)
{
return Json((DataSourceResult)GetProjectsList().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
That is very specific to how the Kendo Grid wants the data back. Nothing else I have connecting to this app will use this data in this format so I keep it in the controller.
In short... I use the API for common things within the same MVC app and things that I allow to be used by other applications or services, like Excel.

Rails MVC concept in practice

I am not actually asking a question but rather an suggestion(or recommendation) on how to write code to fit nicely into Rails MVC pattern. Hope rails veteran or anyone familiar with MVC can give me some feedbacks.
I have an web app that talks to a RESTful api app via ActiveResource. It can fetch and update contents using API calls. It works perfectly. However, the web app does not have any models. The way it works is when user triggers an action(index,view,edit etc), the controller will directly call the REST api to fetch/update data.
My question is: Is it a good practice to do it this way or should I create models and populate data in there instead of directly calling the api? I was wondering if it is just a pragmatic compromise to MVC. I have just started working with Rails(and MVC) so I am open to any ideas, comments or recommendations on this
It's a bit of a catch-22 question. (I did wrote a huge answer but then deleted because it will be too tedious to read)
If you mean, can you implement the MVC pattern without a model, then the answer is no. The M means Model.
If they mean, can you use the MVC without using a model, then the answer is "yes", but it is no longer MVC, you have obliterated the the M i.e. Model.
I would recommend you to read MVC pattern in detail and then try to understand what your application actually trying to do.
http://c2.com/ is a very good place if you want to understand the design patterns.
A model is an object representing data or even activity, e.g. a
database table or even some plant-floor production-machine process.
A view is some form of visualization of the state of the model.
A controller offers facilities to change the state of the model.
Now in your case (it seems): you do have a data coming through via api so I would suggest populate the model properties and propagate it across.
Also Considering Pragmatic Compromise in MVC Dealing with things sensibly and realistically in a way that is based on practical rather than theoretical considerations. Omitting the use of Model in MVC do-not sound like a good idea, and it no longer remains MVC.
Having said that It seems from your point of view you are trying to say that Rails isn't necessarily strictly MVC hence why not use the way you want to :) but I will suggest to keep the integrity of MVC (and follow the purist approach).
http://c2.com/cgi/wiki?ModelViewController
Good read: jeff Atwoods: http://www.codinghorror.com/blog/2008/05/understanding-model-view-controller.html (Feel free to skip the asp.net part)
https://stackoverflow.com/questions/1242908/in-english-what-really-is-model-view-controller
sums it all :) source is mentioned above.
"The model consists of application data and business rules" (wikipedia)
A model is essentially a table in your database locally.
If you're not storing any data, not validating any data, then you don't need a model.
If you want to clean up your code, maybe put some functions in a helper or in /lib

Does having multiple web front ends and a single database back end fit into the MVC design pattern?

We have 3 websites at the moment that all operate off the same database backend and they share almost 100% of the business logic.
It is becoming a pain to have to update 3 website's code every time to accommodate a small change. Would using ASP.Net MVC work for us?
What I am thinking is the business logic and database is almost identical in all 3 so extract that away into the Model and the Control. Then each web front end (which looks different) each has a different View. It would then be Nice to have a single project where we can have all the code for the Model and Control shared. And 3 different views.
How would we deploy something like this? Share a single codebase for Model and Control and have 3 separate URLs using 3 different Views. Or is there a better way to do this?
You can probably pull it off using ASP.NET MVC, but you could also insert a service layer and use standard ASP.NET web services to expose it. Then each of your "views" could still be in its own little world, and just use the web services to grab and persist data.
ASP.NET MVC is probably a better solution in the end, but this is certainly an alternative.
One thing you do need to consider is if you want to keep these 3 sites on seperate domains. I'm not sure how ASP.NET handles keeping different views on different domains.
Sounds like you really need to implement a service layer (encapsulating the common business logic and data) that is used by n (thin) web apps. So think SOA.
This seems reasonable to me. In terms of the model and control you could consider dealing with any minor differences between the current models/controls using shared functionality in a base class and using inheritence to deal with exceptions.
If your web front end is only different in terms of look and feel then you may want to consider using the same code base but just swapping in different themes using CSS.

Of all of the ways that Microsoft offers you to write a web page, which one delivers the most value per programming hour?

I'm frustrated recently by all of the choices that Microsoft offers to develop a web form. There is Sharepoint, Infopath without Sharepoint, ASP.NET Web Forms (with different controls for each runtime), ASP.NET without Web Forms, ASP.NET MVC framework, Silverlight, and WCF. Rendering and databinding technologies aside, there are a handful of different ways to pass data to and from the database (DataSets, LINQ, SqlDataControls, and many more) And those are only the ones that I can name in a minute or so - I'm sure I'm missing some very old technologies (did FoxPro ever get a web front end) or very new things in the process of rolling out of Microsoft Labs.
If I want to move away from using ASP.NET Web Forms and DataSets, what's the best way to move right now for data driven forms? What have you worked with that delivered good value for your programming time? I'm tempted to try working with LINQ to Entities and the new MVC framework, but I don't know enough about all these new technologies to choose where the value lies.
It's been said many times before - there is no "what's best". If any of these tools were best, than the rest wouldn't exist. "Data driven forms" is a pretty broad requirements statement.
They all have advantages and disadvantages in other areas, but all of them are capable of "data driven forms". MVC is lower-level forms - you will have to put in all the HTML and form processing yourself, however, it is much closer to dealing directly with HTTP, so lots of people find it much lighter-weight and easier to work with.
Silverlight has drawbacks in that it uses a diminished set of the .Net libraries, and requires the users to install browser plugins.
WCF would provide the data behind your forms, and would be very suitable if you're planning on opening up a public API or consuming the data in other ways.
You may find it beneficial to research each technology for even an hour each, and you would have a better understanding of which might fit your needs.
If you're using ASP.NET (which, when trying to code a regular website, feels a little "shoehorned"), then I thoroughly recommend trying Microsoft's MVC framework. It's a real breath of fresh air!
From a value per working-hour POV, it really depends on what you're doing. I can't say I've tried many web-frameworks, so I may not be the best metric, but using MVC everything fell into place naturally and I'm happy to stick with it for now.
I don't think ASP.Net Forms is something you need to "get away from".
MVC certainly has it's usefulness and when appropriate certainly makes a lot of stuff simpler.
But a well designed ASP.Net Forms app can be just as or even more useful in certain situations.
Myself I use MVC for public facing sites and Forms for internal/administrative stuff.
For a data-heavy page, I think web forms is a perfectly adequate solution. MVC introduces separation of layers which may make it harder for you to develop, since it forces you to separate the gathering of the data and routing it.
I'd say MVC is nice for having an interactive web page (Web 2.0-ish) but if you are simply showing a bunch of reports, or making users fill out forms - there's not much for you to take advantage of, IMHO.
As an alternative, try writing less code with built-in controls like Repeaters or DataGrids or even DataSets. Getting down to the core of your data flow allows you to be more productive by writing smarter code - not necessarily by writing less code.
In the end, I've found that I put together my own "framework" that does exactly what I need. I get HTML directly from a custom control. These controls simply format the data being fed by procedure calls to my custom Database access class. And yes, these are all served up with web forms or http handlers (ASHX) and a little bit of jQuery.
So while it's not glamourous, it gets the job done faster and better - by developing code that is fine-tuned to my business, not to some abstract software design pattern.

Resources