Best Practices for ASP.NET MVC [closed] - asp.net-mvc

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Basically, this 'question' is intended to pool information about best practices in the community. The reasons for this are:
The distinct lack of an community based ASP.NET MVC resource for best practices. Yes, I am aware of wiki.asp.net.
I'm painfully aware that the ASP.NET wiki on ASP.NET MVC is woefully small and terribly out of date and needs fleshing out more by Microsoft before the community does anything with it.
I'm very much interested in best practices in general, having had a fair degree of experience with ASP.NET MVC over the last year, but I'm also mindful that I'm no expert, and that I can definitely improve. This post, I believe, can help that, and you.
I gave some serious thought on whether or not I should ask this question, even going to the lengths of creating a question on meta about creating this question. :)
What I am looking for is for best practice information on all aspects of ASP.NET MVC. Controllers, models, extensions, HTML helpers, route builders, TDD.
In the past, I have found resources, such as Kazi Manzur Rashid's best practices (part 1 and 2) post quite useful, along with Maarten Balliauw's weigh-in, but these have dried up somewhat, and I was hoping for a more dynamic and growing repository of information from different people, rather than just the occasional blog entry from learned individuals. Information like this is few and far between, and ASP.NET MVC community resources even less so.
MVC in general
Model
Feel free to add model links
Views
Controller
Feel free to add controller links
Guidelines:
One "best practice" per answer
Take the time to explain why it should be preferred over the alternatives.
Read existing answers first - if you see one you agree with, up-vote it; if you disagree, down-vote and leave a comment explaining why.
Feel free to edit any answer if you can expand on why it is "best"!
P.S. Please don't just put "Anything by Phil Haack, Scott Guthrie, Rob Conery or Scott Hanselman"!

Use T4MVC to eliminate all magic strings and magic anonymous types in your entire project. This will help you in refactoring later in your project, and (apart from having to still ensure your routes are well-defined) all Action calls get their proper parameters. It changes calls like this:
<%= Html.ActionLink("Link text", "Products", "Details", new { id = Model.Id }) %>
Into:
<%= Html.ActionLink("Link text", MVC.Products.Details(Model.Id)) %>

Keep any and all logic out of your view. Your controller should determine what gets shown - your view should be dumb.

IoC/DI for Controller factory (so I can inject IRepository, ISomeService in controllers constructor)
never access HttpContext directly, build wrapper, so it can be unit tested
Validation framework for model binding validations (xVal or FluentValidation). Built-in validation inside MVC 1 is basic
never use "magic strings": for calling controllers/actions from View, for RouteLink, RenderPartial, RenderAction, ...
never use ViewData, build DTO ViewModel classes. Use AutoMapper for mapping data from domain entities to ViewModel DTO objects for View
ViewModel DTO objects:
BaseViewModel abstract class, with properties for rendering page meta data, menus and all other stuff that appears on every page. All other ViewModel classes inherits from BaseViewModel.

While not a best practices site, the below site is doing great things with asp.net MVC that could probably be considered best practice.
http://www.codeplex.com/MVCContrib

There are 2 free chapters available for the book "MVC in Action".
http://www.manning.com/palermo/
Chapter 12 is best practices.

Keep your controllers as "thin" as possible. Simply have them validate data coming in from the form, and then calling the model (which does all the real work) to get the data to be returned in your next View.
Having complex controllers kind of breaks the MVC concept.

This is how i handle all DropDowns in my application and i wanna share with you cause i think it's sorta best practice:
One EditorTemplate for all DropDownLists in ASP.Net MVC

Related

Best practice HTML StringBuilder method (ASP.Net MVC)

At first i have to say, i wanted to ask this question on programmers but i don't have enough reputation in this stackexchange.
While i was developing a ASP.Net MVC (4) Application i came to an issue where i had to display data from a model in a view where i need a recursive function which builds the HTML for me.
I asked myself where such a funtionality should be placed in best practices. The model should not hold any logic and the controller does not communicate with the view in common. And i really don't want to put complex logic into my view.
This is a theoretically question and i hope it is ok that i asked in this forum without giving source code.
You are quite right to keep your concerns separate. What you're looking for is a ViewModel.
What is ViewModel in MVC?

MVC 4 / Razor in layman's terms

I'm sorry if this is a stupid or obvious question, but I've spent the better part of a week researching, and I really can't find any resources that explain what MVC 4 and Razor are, and what they are intended to do in web development. I'm not necessarily asking for a really detailed description, even a link to a website or the name of a book that doesn't explain MVC 4 by referencing other technologies that I have also never used. I've looked through articles, articles and tutorials on everything from MSDN to graduate papers and I just don't get it.
I know what MVC the design pattern is, but one of the main things I can't get a straight answer to is what the difference is between MVC the pattern and MVC 4 the framework. As a web developer, will I ever have to change or make use of the frameworks, or is it something that is supposed to "stay out of your way" (to quote another SO post.) Is it something that gets generated by VS and I will never have to touch?
Again, I'm sorry if this is obvious, maybe I'm trying to make this more complicated than it actually is. All I have been looking for is a straight forward answer with concrete examples that don't contradict or complicate it any further.
Please...I'm at my wits end here. My last question was apparently too vague and got voted down and closed, so I tried to be more specific, but part of my problem is what are the right questions to ask.If there is anything that can say to clarify,please tell me.
I certainly don't want to discourage you any more than you appear to be at the moment, but in my opinion, if you can't make head or tail of the huge amount of material that already exists on MVC, then perhaps you are just not ready for it yet. That's OK - in fact Microsoft recognise that MVC is complicated, which is why they introduced the ASP.NET Web Pages framework (which is what gave birth to Razor syntax).
My advice would be to follow the link and download WebMatrix. Then follow some of the Web Pages tutorials. That way you can get your head around Razor without worrying too much about MVC for the time being.
Incidentally, ASP.NET MVC is a web development framework that enables you to build web applications based on the MVC pattern. You need to understand how MVC works in order to make use of the framework. You need to understand what Models are, what Views are and the role that Controllers play in the whole thing.
The framework itself is not an example of MVC.
Razor is a templating syntax that allows you to intermix C# (or VB) with HTML to output dynamic content in a View in MVC or a page in the Web Pages framework.
I know it may seem confusing, but it seems to me that you are over complicating things.
The simple matter is that MVC is a design pattern. That is, it's an abstract thing.. a philosophy of sorts. It's not a concrete thing. A design pattern simply gives you a description of how the pattern is supposed to work, and while it may give you a sample implementation, in general it leaves that implementation up to you.
ASP.NET MVC (whichever version) is a specific application framework that uses the MVC pattern as its basis. In other words, it's a concrete implementation of the MVC design pattern.
In fact, the ASP.NET MVC implementation isn't even a "true" implementation of the MVC design pattern, as certain compromises are necessary to make it work in a web based model. So it's really more "MVC design pattern inspired".
You're overthinking things. Just accept that ASP.NET MVC is a framework library that implements and MVC design pattern.
As for Razor, it's merely a templating library. That is, it allows you to define a page layout as text, and insert values at specific places (place-holders). It also allows code to be executed during the process of rendering a template, although this is discouraged in MVC except for very simple cases.
Razor is also used in ASP.NET WebPages technology, in those cases it tends to be more like PHP or classic asp in that all code exists in code blocks within the template itself. Both ASP.NET and WebPages use the Razor templating engine (also called a View Engine) but they use them in different ways.

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

Blog Architecture Design, using MVC and DDD

I'm designing a blog architecture on asp.net mvc. Lets say i only have 2 entities: post and comment. do i need a controller and a repository for each one? how goes the mechanism for displaying a post with it's comments? do the post controller looks in the posts repository for the post, then asks the comment controller to retrieve all the comments connected to this post, gets them from the comments controller and passes them to the view? or maybe i should write a service which is responsible for querying both repositories and returning the results to the posts controller, which passes them to the view?
Perhaps the first thing to note is what features will your blog have and make available for its primary functions :
editing
subscription
comments
authenticating users - eg identifying the blog owner and posters.
What other ideas will yourblog have ?
Are you going to try out some new Kool ideas that you might not have seen elsewhere ? If so like what ?
The first questions that need answers are your requirements then you can start worrying about architecture and technology stacks and how to codethis or that type questions. Either way your ideas and questions are most eagerly wanted here :)
I'm not sure what ORM you are using, but I would only have a single repository for Posts. When I ask for a Post, all the comments should be attached (lazily or eagerly loaded depending on specific instance). In DDD terms I think you'd describe it as the Posts entity is the root of the 'Posts' aggregate if you want to view it that way.
I don't think there is anything wrong with having two repositories in a single controller though.
You can checkout examples such as
Kigg
Oxite
You might be interested in this other post discussing ASP.NET MVC + CSLA + DDD . It provides nice examples of projects using them together.

What View Engine are you using with ASP.NET MVC? [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 8 years ago.
Improve this question
I know you can use several different view engines with ASP.NET MVC:
ASPX, obviously
NVelocity
Brail
NHaml
et al...
The default ASPX view engine seems to make the most sense to me, coming from an ASP.NET WebForms background.
But, I wanted to get an idea of the pros and cons of each and see what most people are using.
Which does StackOverflow use?
I use Spark. It has nice flow between HTML and code. Scott Hanselman also did a post on it with his weekly source code review posts. I am really digging it a lot. One of the major features is pre-compilation of your views.
"Which does StackOverflow use?"
Web Forms.
I asked Jeff Atwood about his decision on his Tag Soup post. He didn't reply - I think he was busy hunting down a missing closing tag ;-)
NHaml is my favorite for its terseness. People either love it or hate it, given that it looks very different from a traditional "HTML with inserted code" template system like ASPX or NVelocity.
Edit:
#Ben,
There are other view engines which compile down (NHaml is one), so those do support custom HTML helpers. I wouldn't be surprised to see the currently interpreted view engines all eventually end up with a compilation model eventually.
Microsoft has recently announced a new view engine: Razor.
Looks pretty interesting:
http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx
Most people on the planet will just use ASPX because that's what they know. Another excellent benefit is the compiled-nature... so you not only get type-safety and intellisense, but you can get the perf benefit as well.
The drawback that I see is that it's so flippin' verbose. I converted an app to NVelocity and was astounded at how clean it looked. The problem is that there were a lot of things that didn't work with NVelocity (like your own custom view helpers) and there was a severe lack of documentation.
I added a feature to MvcContrib where you can register your own HtmlExtension types to it, but it's more of a bandaid until a better solution comes out.
I've used NVelocity in the past. For the most part it makes the code really clean and simple to follow; however, it normally ends up just being a few ViewData variables which have been filled up by XSLT files before hand. So I guess really my View Engine would be both XSLT (which is a love/hate thing - Extension Methods make it really useful) and NVelocity.
I've used NVelocity with MonoRail for some time but have recently switched to Spark for both Asp.Net MVC and MonoRail. The syntax seems very natural to me, but I guess that's to be expected. ;)

Resources