ASP.NET MVC application structure [closed] - asp.net-mvc

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I am developing an MVC application using a mysql database.
I searched a lot through SO and other sites about the architecture/structure. I found a lot of similar questions but I am still in doubt.
In my applications there is a categories section; the structure is shown below:
View:
Category - (views in category folder listed below)
CreateCategory
DeleteCategory
ManageCategory
Controller:
CategoryController - (action names listed below)
CreateCategory
DeleteCategory
ManageCategory
Model: This is where I have doubts. I have a model named CategoryModels but I don't know if I doing things the right way or not. I don't know where I should put the service functions - for example where I put functions to create or delete categories.
What I did is create a CategoryServices class inside CategoryModel.cs and write functions inside that. DAL file is put in app code folder, so to access the DB the function will create an object of DAL and call it. Is this the right way?
In CategoryModels.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Mvc;
using System.Web.Caching;
namespace TraktorumMVC.Models
{
public class CategoryModels // contain properties for the 3 views (CreateCategory,DeleteCategory and ManageCategory
{
public IEnumerable<SelectListItem> CategoryList { get; set; }
public IEnumerable<SelectListItem> AvailableCategories { get; set; }
//etc..........
}
public class CategoryServices // this class contain all service functions related to categories
{
public int RemoveCategory(int categoryId) // this will remove a category
{
int status = -1;
try
{
string query = Resources.Queries.RemoveCategory;
DAL objDAL = new DAL(); //DAL file is in Appcode folder. IS this right way
string[] inParamNameArray = { "Id"};
string[] inParamValueArray = { categoryId.ToString()};
object[] inParamTypeArray = { DbType.Int32 };
status =Convert.ToInt32( objDAL.ExecuteScalar(query, inParamNameArray, inParamValueArray, inParamTypeArray, true));
}
catch (Exception ex)
{
DeveloperLog.WriteExceptionLog(ex, "CategoryServices.RemoveCategory");
}
return status;
}
public bool InsertCategory(int parentCategoryId, string icon, string name)
{
//bla bla
}
}
}
Is this right way to do this? Did this break the model concept?

The "Model" in ASP.NET MVC is not very prescriptive, and is certainly less prescriptive than the Views or Controllers.
That said, there isn't necessarily a right or wrong way to do your model, but there are a few popular/common approaches that people take:
Leverage an ORM like Entity Framework (EF) or NHibernate to be your model. This works out well on simple sites that are mostly CRUD driven. In your situation, EF could handle all of the CRUD work you need to do on categories.
Another common approach to is to leverage some sort of services layer which might encapsulate business and data access logic. This layer might return to your application data transfer objects - very simple, data only containers - that you can change and send back.
Either way, it's a good idea to separate your "View Model" from your "Domain Model". An example of this is not simply passing Entity Framework controlled objects to the View for rendering. Instead you'd map those objects (and potentially others) into a "View Model" specifically created for just that view. A popular tool to help developers accomplish this is the excellent http://automapper.org/
In your situation, if you can, I'd recommend putting in an ORM to handle the persistence of categories. If your current DAL is doing more than just persistence, then I'd recommend you separate it out to a service, with corresponding interface, that your controller can get a reference to and use to drive your application forward.

You don't really have a Category model here, what you have is a view model for a particular part of some views. As #nikmd23 alludes to, you probably want to separate your view model and domain model. A domain model is something that describes the data which makes up your system. A view model is something that describes how you would like to share that data through an interface.
In this case, start by creating a domain model, something like:
public class Category
{
public string Name { get; set; }
public int Id { get; set; }
}
Then your DAL contains some functionality for getting a collection of Category objects:
public interface DAL
{
IEnumerable<Category> GetCategories();
}
And when you want to construct a view model of your categories, you would map it to view model:
var dal = new DALImplementation();
var categories = dal.GetCategories();
var categoryListViewModel = categories.Select(m => new SelectListItem
{
Text = m.Name,
Value = m.Id.ToString()
});
There are many different implementation patterns for each of these steps, but the whole idea is to start by creating a domain model, then build your services to interact with those domain models, and for each request with a view, construct a view model which only shows the exact information you want to share with your user.

Related

Dynamically change models and controllers after publishing website in ASP.NET Core MVC

I'm using ASP.NET Core MVC 2. I need to operator can change some elements of Models or view codes. How I can code or design for it.
For example: I have a "news" model and I want to operator (final user of website, who can't code or access to visual studio) can add this to "news" model:
public string ImageUrl { get; set; }
and also can change the database without coding.
Thanks
If you want to design a completely extensible model, you could use something called Entity–attribute–value model (EAV).
Your model might have a couple common attributes like Title and Summary. Then you might have a list of Custom Fields, the first of which could be ImageUrl. You could create your own class called CustomField or something similar, which would have properties such as FieldName, and DataType.
public string Title { get; set; }
public string Summary { get; set; }
public List<CustomField> CustomFields { get; set; }
You would then have a table full of custom field values and the tables they belong to. It gets pretty complex.
When you want to automatically reflect your model changes to the database, you will need an ORM framework like EF (Entity Framework). You can check more here.
In order for your case to happen is to build your own configuration platform that may use several tools and mechanincs that will allow you to generate code and then compile it. Such as T4 and more.
In general, this is a very hard task to accomplish and even big experienced teams would have troubles to build something similar.
I can not post any code, as this would only seem a desperate approach.

ASP.NET MVC + Entity Framework - How to deal with DTO's and ViewModel's [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'll try to describe a problem that I see very often in my workplace, but I couldn't find a way or a reasonable solution to it. I searched a lot about this and all I could find is what I already have implemented. The scenario is this:
I have an ASP.NET MVC app using Entity Framework which follows the Repository Pattern. I will use a simple Student/Teacher database structure to exemplify
Entities
public class Student : BaseEntity
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public Teacher Tutor { get; set; }
}
public class Teacher : BaseEntity
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Student> Students { get; set; }
}
public class BaseEntity
{
public byte State { get; set; }
public Datetime CreateDate { get; set; }
public Datetime UpdateDate { get; set; }
}
Now, let's say I need to expose a method to return a list of student names along with its teacher's name:
var students = context.Students.Include(x => x.Teacher).ToList();
The query above is bad and we all know it, since it returns all columns. Now, if we refactor to this:
var students = context.Students.Include(x => x.Teacher)
.Select(x => new
{
Name = x.Name,
TeacherName = x.Teacher.Name
}).ToList();
I'll have a performant query that select only the fields I want. That's good. But now I need to make a choice. To return this list to my controller, I can either: Create a StudentDTO, or populate a Student instance with only the columns I selected in my query.
DTO approach
If I create a DTO and pass it along to my controller all will be "fine". No worries with extra unnecessary fields.
Return EF Entity Student
If I return the database entity to my controller as is, even though I loaded it with only the fields I wanted I will get all the other empty fields. So I create a ViewModel to return only the data I want. (This is what we are doing right now in most methods along with AutoMapper)
Problem:
See the pattern? Either way I will ended up creating a class to map my return. I'm fine with this most of the time, but in the project I'm working right now, we have several methods to expose and each of them has a different return structure. For example, what if I wanted to return a list of students that contains only student Id and Name? Create another DTO or ViewModel?
The project has a team of 5 developers and the ViewModel folder is getting pretty stuffed with classes. I started instructing them to return an anonymous object inside a controller when a method return is very specific. I only create View Models now when I'm sure it can be re-used elsewhere.
But this anonymous approach had become also bad because now I have to do this in several controllers and I feel I'm repeating myself.
Is there any other approach I can use to solve this? Of course the project I'm talking about is much more complex than this example, with several entities and pretty complex queries. I feel this happens a lot in other projects and I failed to find a decent way out of this.
I wish I would have stumbled upon this question a year ago. Hopefully this info helps you or someone else even though its been awhile.
You are exactly right. You see a problem and your gut is already telling you there is an architecture problem and you are right.
I know it is a pain but the DTO approach is the correct architecture in my opinion. These classes are a pain to create and use and we have all tried to shorcut around them at some point. But, you should be inheriting from base classes to share properties between objects to ease your pain. Also, use a 3rd party open source tool like automapper to move data easily between your data models and your dto objects.
Developers make this architectural mistake all the time (trying to bypass the DTO object) especially if they are working on smaller software systems and not large corporate enterprise systems where the above architecture will fail fast while it may succeed forever in a small system.
using your first example:
var students = context.Students.Include(x => x.Teacher).ToList();
You would then copy students into a dto object (perhaps StudentDTO) and then pass this up to your UX and translate it into a viewmodel object. If Student and StudentDTO are identical then they can inherit from the same base class and StudentDTO gets created with about one line of code.
Using your second example
var students = context.Students.Include(x => x.Teacher)
.Select(x => new
{
Name = x.Name,
TeacherName = x.Teacher.Name
}).ToList();
If you do not do this and instead translate everything into a ViewModel then you will end up with endless viewModels as you have.
However, even more importantly here, you shouldn't be able to move it into a viewmodel because ViewModels should sit in your UX layer and the fact that you can do this would indicate a small architecture issue on its own. ViewModels are only applicable to the UX and not anywhere else so keep them in the UX layer.
If you move your viewmodels into the UX you would find that you could not move your EF objects into your View Models and this would have steered you down the DTO architecture approach instead.
So why dont you just pass EF models up to the UX?
Well, you can. Works good in simple scenarios when you are just editing a single student for instance. This is tempting because its so easy to do and it works so why not do this?
For very simple, small systems please do. I think this is fine. you can pass an EF model up to the UX, translate it into a viewmodel and then the viewmodel back to the EF. To do this your EF models should sit outside your data and ux layers in their own layer. I typically use a dll called something like "MySoftwaremName.Common". I place all interfaces, data models and dtos in this layer and reference this layer from the UX, Service and Data layers so that DTOs and interfaces can easily be passed up and down the architecture.
My primary real world experience has shown that the primary reason you do not pass EF models directly up to the UX is Caching.
In small systems developers may not deal with this so this may work just fine. But in large systems where we are getting hit 50,000 to 100,000+ times a second caching is key.
What if you wanted to cache your student object so that it could be retrieved for the next 5 minutes without you hitting the db over and over again.
You cannot cache the EF models in ASP.NET or you will eventually encounter severe issues that are occuring randomly in your system that are hard to trace down.
You can stick the EF objects in Cache and even retrieve them from cache. However, EF entities are attached to Database Context objects and that context eventually goes out of scope and gets garbage collected by .NET. If you still have your Student object in cache after this happens and you retrieve it and try to use it (using your own example again) to get the Teacher subclass "Student.Teacher"
you will get the yellow screen of death if that Teacher object is not eager loaded and is lazy loaded By EF. Ef will try to use the context to go fetch that Teacher and there isn't one and it will blow up.
To prevent all this it is best to move your EF objects into DTOs and then you can safely tranfer this data, cache it etc without any worry.
The only pain in this architecture comes in translating DTOs to viewmodels and EF models exactly as you have stated. But as I mentioned above, using proper base classes to share fields and using something like AutoMapper or another Mapping engine will help you map quickly from DTOs to ViewModels and EF objects.
Always create a ViewModel. The ViewModel is a UI concern. your entity framework model is a domain concern. ViewModels aren't about re-use. They are about defining only what you need to satisfy the View that uses them.

ASP.NET MVC Done Right: View Models

I read this q/a Real example of TryUpdateModel, ASP .NET MVC 3 and was really interested on #ben-foster response.
I started doing a comment on that answer but got quite long, so started a new Question.
Having ViewModels for everything approach (which i like a lot) get me into some 'weird scenarios' that i want advice in how should I do.
Imagine this structure :
public class ProductListEditableViewModel {
List<ProductEditViewModel> products {get;set;}
}
public class ProductEditViewModel {
List<PriceViewModel> prices {get;set;}
}
public class PriceViewModel {
CurrencyViewModel currency {get;set;}
}
and so on ... ? do you really make one view model for each inner class? how then you map all that to the Model Object?
Also, that covers the Edit, but I have an Add, a send via email, and potentially more Views so more ViewModels!! should i end like something :
AddCurrencyViewModel
QuickAddCurrencyViewModel
EditCurrencyViewModel
ListCurrencyViewModel
DeleteCurrencyViewModel
ShareCurrencyViewModel
all having the 'almost same' properties ?
Should all those be packed into one file ?
Also do i need all this all viewModels or a inheritance approach might be better?
If you can, I´ll appreciate elaborate on complex scenarios
Also, I use a DTO approach to expose some of the model objects into web service / apis, so I already have some form of mapping already in place where this DTO are not exactly my ViewModels, should I remove one of them? what´s the suggestion in this scenario ?
I´m using entity framework but i think the question is (or should be) ORM agnostic.
Not using UoW pattern (will this helps?) as looks it´s gets more complicated as the depth of the object increases.
Thanks a lot!
We typically have a view model per view so yes, if you have lots of views you will have lots of view models.
In typical CRUD applications we often have very similar views, for example Add and Update. In these cases, yes we use inheritance rather than writing duplicate code - usually Add subclasses Update.
public class AddFoo : UpdateFoo {
public AddFoo() {
// set up defaults for new Foo
}
}
public class UpdateFoo {
public string Name { get; set; }
// etc.
}
We attempted to "share" view models between views in the past and normally ended up in a world of pain.
With regard to your "weird scenario" - this does look weird indeed, but perhaps because I don't understand your application.
The goal of your view model is to provide the information to the view that is needed and ideally to flatten any complex objects so they are easier to work with. You shouldn't split your view models up like your example unless it makes sense to do so.
Let's say I wanted to a create a view where the customer could change their contact details. Taking the following domain object:
public class Customer {
public string FirstName { get; set; }
public string LastName { get;set; }
public Address Address { get; set; }
}
I'd probably flatten this to a view model like so:
public class UpdateAddressModel {
public string FirstName { get; set; }
public string LastName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressCity { get; set; }
// etc.
}
Of course there will be occasions where it doesn't make sense to do this, for example a dashboard view in an online store where you have a list of products going out of stock and a list of recent orders - these two things are unrelated but are required by your view:
public class DashboardModel {
public List<Product> ProductsGoingOutOfStock { get; set; }
public List<Order> NewOrders { get; set; }
}
how then you map all that to the Model Object?
I'm assuming by Model Object you mean your data/domain model. The key takeaway here is that the view model you use to render your view is unlikely to be the same as the "models" you POST to the server and if they are, you're probably over-POSTing or you have some crazy enter-everything data capture screen that will make your eyes bleed.
I find it helps to think of what you send to your server as Commands and what you use to render your views as view models.
So the answer to your question - how do you map your complex view model to your data model? - Quite simply, you don't. You should send commands to the server that perform a specific task e.g. updating an address.
There's no hard and fast rule in how you structure your view models but generally go with what makes sense and if it starts to feel too complicated you're probably trying to do too much with one view.
I hope this helps. You'll find lots of posts relating to this matter on my blog.
I realize this is an old-ish question but I did want to address one of the questions posed by the OP that was not answered.
Should all those [ViewModels] be packed into one file ?
Most of the examples I see put each ViewModel in a separate file, so the dominant convention seems to be one file per viewmodel, but I found in practice that this seems to be overkill. Instead I put all viewmodels for a particular controller in one file with multiple viewmodels in it. So for example if User is my Controller and I have several viewmodels associated with this controller such as UserAddViewModel, UserEditViewModel, UserDeleteViewModel I put all of the viewmodels for User in one file called UserViewModels.cs

ASP.NET MVC 4 project without any ORM [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to use ASP.NET MVC without EF and possibly without LINQ. To start with I created just one table/model/controller/view on basic ASP.net mvc template in VS2010(Just index page and Index method is implemented). I am currently going with try/error as all tutorials on the web are based on EF and I have an embedded c background.
My questions are:
Is the architecture correct?
I saw repository pattern is used in some open source projects such as nearforums. What's its advantage and how does it fit into this, does it replace DAL?
Should I pass datatables to view or objects representing the datatable?
Can I pass more than one model to razor page? How can I list 2 different tables for example?
Is it better to put all DAL code in one file?
DAL:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using MySql.Data.MySqlClient;
namespace MvcApplication1.Models
{
public class DAL
{
public DAL()
{ }
public DataTable getDataTable(string tableName)
{
using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConn"].ConnectionString))
{
using (MySqlCommand command = conn.CreateCommand())
{
command.CommandText = "select * from " + tableName;
command.CommandType = CommandType.Text;
conn.Open();
var table = new DataTable();
table.Load(command.ExecuteReader());
return table;
}
}
}
}
}
Product.cs class that represents Product table in the code:
namespace MvcApplication1.Models
{
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Producer { get; set; }
public int UnitPrice { get; set; }
}
}
ProductController.cs
namespace MvcApplication1.Controllers
{
public class ProductController : Controller
{
//
// GET: /Product/
DAL dal = new DAL();
public ActionResult Index()
{
DataTable dt = dal.getDataTable("Product");
Product[] products = new Product[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
products[i] = new Product();
products[i].ProductId = (int)dt.Rows[i]["ProductId"];
products[i].Name = (string)dt.Rows[i]["Name"];
products[i].Producer = (string)dt.Rows[i]["Producer"];
products[i].UnitPrice = Decimal.ToInt32((decimal)dt.Rows[i]["UnitPrice"]);
}
return View(products);
}
........
........
}
Index.cshtml:
#model IEnumerable<MvcApplication1.Models.Product>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ProductId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Producer)
</td>
<td>
#Html.DisplayFor(modelItem => item.UnitPrice)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ProductId }) |
#Html.ActionLink("Details", "Details", new { id=item.ProductId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ProductId })
</td>
<br>
</tr>
}
I saw repository pattern is used in some open source projects such as nearforums. What's its advantage and how does it fit into this, does it replace DAL?
The benefits of the repository pattern are that it allows you to switch out your data access logic/ORM. For example, if you wanted to switch from Entity Framework to NHibernate, you just update your registrations inside you IoC container and like magic your code is using NHibernate with 0 knowledge of you ever making the switch. It allows your code to be agnostic of the underlying persistence framework. For all it knows, results code be coming from a file, web service call, or an in memory list. You'll also get reuse in the event that you had to make the same query from another component. Another gain is unit testing. With your current implementation, you cannot unit test your controller as it's going to connect directly to your database every time, thus by definition making it an integration test. You will certainly want to leverage an ORM, or you'll be writing the same code over and over again until it makes you cry. Setting up/tearing down connections, type casting all your primitives to native .NET types, etc. Dealing with native ADO.NET is a thing of the past nowadays. Make your life easier and use an ORM. At the same time, with great power comes great responsibility. ORMs can be a nightmare if you don't validate the queries that are being generated and executed against your database. If not used properly, they'll generate performance problems. You'll be able to leverage LINQ for most of your queries, but sometimes you'll have to get dirty funky native and go with raw SQL. You ORM will still be able to handle both scenarios.
Should I pass datatables to view or objects representing the datatable?
You certainly don't want to pass datatables. You want to pass view models or entities to your view. The view should know nothing about the database. All you do is give it data, and it displays in on the screen not ever knowing the source of that data. You want to be careful with passing entities directly to your view if you're using something like NHibernate, because you run into problems associated with lazy loading and N + 1 queries. View models are typically slimmed down versions of your entity. For example, if you had an entity with 4 properties but the view only needed to consume 2/4 of those properties, you'd make a separate view model with 2 properties and use a mapping library like Automapper to map from your entity to view model.
Can I pass more than one model to razor page? How can I list 2 different tables for example?
This is quite simple. You make a top level object and give it 2 properties to represent the entities you want to access.
public class MyViewModel
{
public Entity1 FirstObject { get; set; }
public Entity2 SecondObject { get; set; }
}
Then you'd make a strongly typed view and render FirstObject and SecondObject using the strongly typed view helpers you used in your razor view posted in your question. #Html.TextBoxFor(), etc.
Lastly, your controller would accept MyViewModel as an argument and populate FirstObject and SecondObject based on the form inputs rendered in your view.
Is it better to put all DAL code in one file?
You want to put related DAL code in the same file. Things are typically mapped out by table but that all depends on the relationships between your objects (what's your aggregate root for example). What you don't want to do is blindly implement one repository per table. You'll just end up with a really procedural and anemic data model that results in stitching together object graphs and relationships via multiple calls to the database. I'd recommend looking into Domain Driven Design to get a good idea on how to tackle this problem.
I've just scratched the surface here. You'll basically need to pick up the latest patterns and practices if you want to do this stuff properly. It's a different movement all together. Not like the good old days of monolithic code behind files, view state, and DataGrid controls. There are some really good books out there like:
Brownfield Application Development
Domain Driven Design (Eric Evans)
Clean Coder (Robert C Martin)
Refactoring: Improving the Design of Existing Code (Martin Fowler)
Patterns of Enterprise Application Architecture (Martin Fowler)
I'm not saying read all these books verbatim, but I'd strongly recommend the first 2. I'm sure the community will have even more to say about these development practices, but this is my perspective on it all. Thanks and good luck.

Why does the interaction between model, view and contoller look different?

Im new to ASP.NET MVC, trying to learn the basics.
Im now trying to learn the relationship between the model ,view and controller.
The interaction between these three looks different, why? (Look at the arrows)
Source 1: MSDN
Source 2 (Page 65): Steven Sanderson
I would be glad if you help me sort out my confusion
Thanks
Edit:
What you are saying is that mvc can be implemented differently?
(Still asking about asp.net mvc - Not mvc in general)
I have been looking at the mvcmusicstore
and it looks like this.
Controller:
public ActionResult Details(int id)
{
var album = storeDB.Albums.Find(id);
return View(album);
}
Model:
public class Album
{
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public string AlbumArtUrl { get; set; }
public Genre Genre { get; set; }
public Artist Artist { get; set; }
}
view:
(Had to add as image, add code the normal way did not work)
This looks like the MSDN version, how would this be rewritten to fit Sandersons diagram?
Maybe this will help me understand!
Edit again:
Hi again
Let me sum this up. Please respond if I'm wrong.
The way Microsoft intended us to use mvc is the one we see in the above MSDN link and in MusicStore.
Then there are other "versions" of mvc such as Sandersons (or whereever it originates from).
So Microsoft give us a basic way of how to use the mvc framework, but it is ok to do it other ways.
A newbie should not get stressed by seeing different versions, sticking to the one seen in MSDN/MusicStore is perfectly fine.
The key difference is the inclusion of the "Presentation Model" in Sanderson's diagram. The ASP.NET MVC implementation often uses the Model as the Presentation Model, even though they can be different (and I would argue that they should be different, but it's a holy war and there's no need to get into that).
In most very simple ASP.NET MVC applications, the model is the data entity. Whether it's an EF entity or a Linq2Sql entity, makes no difference. This is because most applications are simple forms-over-data and the presentation is probably one-to-one with the persistence.
The MVC pattern itself, however, doesn't require this. In a more pure framework-agnostic form, Sanderson's diagram illustrates the fact that the controller is interacting with the model. The model is really the "gateway to the domain core" in this sense. Controllers and views are part of the application, but the model has the underlying business logic and, beneath that, layers of persistence and other infrastructure information (properly separated, of course) which are unknown to the application. The boundary between the controller and the model is the application boundary, the point at which other applications can also connect to the domain core and interact with it.
A presentation model is usually nothing more than a simple value object. It's not an entity of any kind in the sense that it doesn't have to exhibit any business behavior or maintain its lifecycle the way that a persistable business entity would. It's just a flat object with some attributes of data.
It can have some behavior, but that behavior is for the application and not for the domain core. For example, maybe it has some methods or properties that the view can use. The presentation model is part of the application, so it's presentation-layer-aware. Essentially it just holds data that the controller needs to pass to the view (or even receive from the request, depending on the framework).
In ASP.NET MVC you'll very often see the model used also as the presentation model. The same object may be playing two roles in those cases, but the two roles are definitely different.
Edit: Just noticed your updated question...
In that example, Album is playing the role of both domain model and presentation model. (In fact, I would argue that it's not a domain model at all because it's too anemic. Notice that it has no functionality, just bare data.) In a richer domain model, Album would likely have more functionality. For a contrived example, imagine that instead of auto-implemented properties it has properties which enforce business logic when set, and it has methods on it such as AddSong(Song song) and Play() and other such behaviors.
This richer model can still be used as a presentation model, but the functionality might not make sense in the scope of a view. A view is really suited more toward just bare data elements. The controller would interact with the model's functionality. So you might create a presentation model similar to the Album domain model in structure, and it would look just like the one in your example.
Going forward, what if the view needs other data as well? Maybe the view needs to know something about other models which aren't part of the same aggregate as Album. It wouldn't make sense to modify the domain models to accommodate the view. That's backwards. The presentation should wrap around the domain core, not the other way around. So you might add properties to the presentation model which are populated from other things inside the controller.
So you might end up with something like this...
Domain model:
public class Album
{
public int ID { get; private set; } // might need to be immutable
private string _title;
public string Title
{
get { return _title; }
set
{
// don't allow empty titles
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentNullException("Title");
_title = value;
}
}
private Album() { }
public Album(int id, string title)
{
ID = id;
Title = title;
}
public void Play()
{
// some implementation
}
public void SomeOtherMethod()
{
// some implementation
}
}
As the business domain grows and changes, this model could change with it. The main point is that it changes at the behest of the domain core and the business logic, not at the behest of UI implementations.
A particular "page" on a particular website which uses this domain core may need specific information about an album, and maybe some other information as well. You'd tailor a presentation model to fit that:
public class AlbumViewModel
{
public int ID { get; set; }
public string Title { get; set; }
public string Owner { get; set; }
public IEnumerable<Listener> Listeners { get; set; }
public string SomeCompletelyUnrelatedValueNeededByTheView { get; set; }
}
The controller would then construct this presentation model for the view:
public ActionResult Details(int id)
{
// TODO: validate and sanitize any inputs
var album = AlbumRepository.Get(id); // after all, why bind the UI _directly_ to the DB? that's just silly
var someOtherObject = SomeOtherRepository.Get(someOtherValueFromSomewhereElse);
var albumVM = new AlbumViewModel
{
ID = album.ID,
Title = album.Title,
Owner = somethingElse.SomeValue,
Listeners = someOtherObject.GetListeners(album),
SomeCompletelyUnrelatedValueNeededByTheView = "foo"
};
return View(albumVM);
}
This is a much more manual approach overall. It's useful when you have more complex domain models, multiple complex applications interacting with that domain, different technology stacks throughout the domain, etc. For simple forms-over-data applications the standard ASP.NET MVC implementation usually works fine. Most of the tutorials for it reflect this, consolidating multiple responsibilities into fewer objects, using decorators instead of explicit code (assuming the use of the same stack of tools across the board), etc.
The examples you're looking at get you to a working application very quickly with very little code. As with any framework, it works beautifully if you do things the way the framework intends you to do them. If you need to step outside the bounds of the framework, you can still maintain the pattern in a more abstract and framework-agnostic way.
Edit: For your update again...
In a way, yes. ASP.NET MVC is a framework which borrows a lot from the MVC pattern in general. As with all things, there's more than one way to do it. Sticking with simple implementations and quick applications, the functionality provided by the ASP.NET MVC framework and explained in its various tutorials is perfectly acceptable and is a great example of the use of a framework... Using a tool to get a job done.
They stick to the pattern in all the most meaningful ways. At the same time, however, in the true nature of a framework (which is generally outside the scope of a pattern description), they try to give you tools which make very light work of the actual development. If you don't have a pressing need to separate your domain models from your presentation models, you don't have to. One model can play both roles. If you don't have a pressing need to abstract your data access behind, say, a repository pattern, you don't have to. You can throw together some quick Entity Framework functionality directly in your Models and be done with it.
Ultimately it's up to the needs of the project, the preferences of the developer(s), and so on. The patterns are more academic, the frameworks are more pragmatic. Balancing the two is the key.
I guess the distinction is that in asp.net MVC you can have strongly typed views which have 'knowledge' of your model and the entity being passed through to the view. In its purest sense though the View shouldn't (or rather, neednt) have any knowledge of the model. For that reason I say Steven Sandersons example is better.
Fantastic book by he way!
I wouldn't sweat it - Stephen Sanderson's diagram is showing less of the cycle but in more detail.
I'd interpret the MS article arrows as:
Controller populates model (from services, etc)
Controller directs to view
View populates through binding model
The microsoft diagram isn't really that useful or informative or useful though in my opinion. You could equally argue that arrows could go in different directions - or even in both directions like Sanderson's do. E.g. Controller also received models from binding, etc.
The Sanderson arrows are annotated well and are self-explicit, and the book is great.

Resources