ASP.NET MVC State Management - asp.net

I am working on a .net mvc web application that has a bunch of web parts on the homepage. I realize that a webpart is a .net forms terminology, but wasn't sure what to name those mini sections. So anyways, for now these sections are called when that page is rendered, but eventually I will plug in JQuery and call these sections using AJAX. These mini sections or widgets will need to keep state as the user navigates between the homepage and back. With .net forms, the page state info is kept in the viewstate, but with .net mvc, that is not available (thankfully).
So, is there a framework already created for such functionality for MVC? If not, what would be the best way to handle this situation? I was thinking to leverage the HttpContext object and store everything in there, but not sure if that object has any size limitations.

Just like with anything else in MVC you're going to need to store the state somewhere. As other users have pointed out, using Partial Views will reduce the complication of the design by allowing you to have controllers that handle just those small parts. They can then be responsible for saving/restoring/tracking the state or info for that part. (This could be using a database, in process memory, whatever.)
If you put the controls in the master page you can have the parts' implementation removed from your other logic so you don't need to worry about capturing and returning data related to those parts with the rest of your model meant for your view.
Having the parts separate like that will make it a lot easier to AJAXify them as well since they would already be operating independently of your view data even though they are rendered at the same time.

I think you want to check out Partial Views.

You can use output caching or data caching, both supported by MVC 1.0/2.0.

Not sure if you're after this but project Orchard has a notion of widgets: http://www.orchardproject.net/docs/Default.aspx?Page=widgets&NS=&AspxAutoDetectCookieSupport=1.

Related

Why can't I use server controls in ASP.net MVC?

I'm getting ready to be responsible for leading the development of a small ASP.net MVC application. This is my first time creating an MVC application, so I am excited!
I've carefully read over the documentation and I feel like I have the general idea of how MVC works. However, if I understand correctly, server controls (like GridView, for instance) are not part of MVC.
My question is: Why? At my development shop, I'm so used to using controls like GridView and the MS Chart Controls that I'm almost at a complete loss as to developing without them. It seems almost like starting over.
Why are the server controls unavailable? How does Microsoft expect me to work without them? What are the alternatives?
My question is: Why?
Because most of them depend on things like ViewState and the Postback models which are part of the classic WebForms model and no longer exist in ASP.NET MVC. Those server side controls rely on events that will perform postbacks to the server persisting their state in hidden fields (ViewState). In ASP.NET MVC you no longer work with events such as Button1_Click. In ASP.NET MVC you work with a Model, a Controller and View. The Controller is responsible for receiving user requests, querying the Model, translating the results into a view model and passing this view model to the View whose responsibility is to display it under some form.
In ASP.NET MVC there are HTML helpers that could be used to generate some reusable HTML fragments between views. You may take a look for example at the Telerik ASP.NET MVC suite of such helpers. They call them controls but they have nothing to do with classic WebForms server side controls. They are just HTML helpers.
Basically classic WebForms are a leaky abstraction of the web. What Microsoft did back in the time when they designed this framework was to bring existing Windows developer skills to the web which was getting more and more momentum. But since the web was still a new technology that most developers weren't yet familiar with, they created this abstraction to hide away the way that the www works. Those developers were accustomed to drag and dropping controls on their Windows Forms, double clicking on buttons that was generating some code for them in which they put their data access logic and so on. This model was transposed to web application development thanks to WebForms. The HTTP protocol was successfully hidden behind this abstraction called WebForms. For example you don't need to know HTML, nor Javascript, not even CSS in order to create a website using WebForms which is really great because the framework abstracts all those things for you. Unfortunately by doing so it prevents you from easily utilizing the full power of lower level web technologies which some people might need when developing web applications.
What ASP.NET MVC does is basically remove this leaky abstraction and bring the www to the developers the way it was intended to be by its creators. ASP.NET MVC is not mature enough compared to classic WebForms so you cannot expect to find the same range of available controls and widgets but things are slowly shifting.
I would recommend you start here with ASP.NET MVC: http://asp.net/mvc. Go ahead, watch the videos, play around with the samples and see if ASP.NET MVC is for you or not. And of course if you encounter some specific difficulty or question don't hesitate to come back here and ask it.
I'm so used to using controls like GridView and the MS Chart Controls that I'm almost at a complete loss as to developing without them. It seems almost like starting over.
In this case, starting over is good.
I've gone through a similar journey. If straight HTML scares you, try working with the System.Web.UI.HtmlControls namespace. This will allow you access to standard HTML controls, but you'll still have the comfort of turning them into server controls if you need to (either by specifying the runat="server" attribute, or by converting them into equivalent ASP.NET controls.
In addition to Darin's answer, there's another problem with ASP.NET: you're bound to Microsoft's view of the web. That GridView you love? It's generating bad HTML. The Paging controls it provides? Even worse. Even if you know very little about HTML compliance, nested tables should give you the chills. In a way, everyone who uses a GridView is lucky that legacy web supported by Microsoft (and to a lesser degree, Google and Mozilla) came from such a god awful starting point.
Finally, to summarize: my suggestion is that you try to rewrite your pages or develop new web applications (as best as you can) using HtmlControls only. You'll probably have to learn some JavaScript/jQuery, and might have to venture into the world of AJAX to make your controls operate the way you want them to.
Use this as a stepping stone into the world of MVC. You won't use the same technologies (and may drop a lot of JavaScript/jQuery), but it will help you change the way you think about web development in much smaller, and perhaps easier-to-absorb chunks.
Ultimately, however much you like your ASP.NET controls, you'll have a much greater degree of freedom, and you'll also be developing websites that make use of newer technologies, which will provide added value to your websites.
At the core of this is Model View Controller (MVC) which promotes decoupling. The idea is that you feed your View (web page) a Model with all the data that it needs to be rendered. Server controls are tightly coupled. There is no concept of state in MVC or 'should' be no concept anyways.
That's kind of the point of MVC. It takes away the high level of UI abstraction that server controls provided and leaves you with html and javascript. (It also adds some really cool model binding features)
I am new to MVC and have found using Partial Views to be similar in creating small, reusable UI elements that do not fit into the _Layout. For example, sliders, slideshows, navigation, featured sections although you can use #section for this I find partial views to be more beneficial. This concept enables me to create reusable libraries that I can switch out easily and use in other projects. To me this is similar to controls, although there is a debate both for and against this analogy.

Quick methodology to show client a working demo

I am not starting an argumentative discussion here and this post is not about career development, but from the commercial point of view:
If a company was using ASP.Net MVC as a main methodology to build their web sites and application.
However, ASP.Net MVC takes more time to show a functional application than ASP.Net Web Forms, for example, building domain models would take some time which obviously can't be represented on a UI at that current stage.
My question is, if a client wants to see a functional demo application (just a proof of concept) so he knows that the company he is dealing with is professional and capable of doing that. Would it be better to do that demo in ASP.Net Web Forms only to show the client, and then work on the real application using ASP.Net MVC? If not, what are the (quick) alternatives?, I mean, if we tell the client to wait till we have a working demo (by ASP.Net MVC) we may lose the client and the whole project opportunity.
WebForms being faster than MVC is a myth:
You are not required to have a domain model, just something that represents your database tables. This is the same in WebForms unless you are using SqlDataSource's.
The code in your !IsPostBack or btnSubmit_OnSubmit is almost identical to the HttpPost controller actions. Except with MVC you don't have to write left to write object.FirstName = txtFirstName.Text when you understand how UpdateModel works.
UI is UI. If you know HTML/CSS creating the UI is just as easy. Almost easier in MVC because you don't have to set control properties any longer and all UI can be done in one place.
Fast MVC comes from understanding how to get the most bang from your buck using EditorFor, DisplayFor templates. You'll need to know and understand how to customize your Object.ascx file. With this technique under your belt you won't have to create forms by hand anymore. 2 projects ago we had a site with 100% autogenerated forms. Change a class, change a form. Done!
Another helpful MVC tool is the DataAnnotations attributes. Validation made easy. Customizing these is really easy too. Just create your own ModelMetaDataProvider and starting expanding the validations your application can handle.
The only part of MVC that is slower is displaying a grid. MVC 3 already has a useful grid tool and MVCContrib has had a grid tool out for a year now. I ended up rolling my own, its very simple actually, loop through properties, write <td />'s. < 200 lines of code. This isn't really a benefit to WebForms either. To use WebForms grid components means giving up a lot of quality using ObjectDataSources and the like.
To summarize fast MVC comes from these different techniques:
Object.ascx
ModelMetadataProviders
UpdateModel
DataAnnotations
If you are more advanced and know ORMS like EntityFramework and how to use Automapper your probably going to be even faster.
You can get a demo up and running very quickly in MVC. I could put one together much quicker than with WebForms, and I am familiar with both.
The reliance on convention in MCV will help a lot, binding is based on the names of objects.
If i was creating a quick demo, i would just create a bunch of ViewModels with static data in them, different button clicks etc will just bind one of these ViewModels to the page.
Turbo Fast!
I build prototypes in excel. No logic, no code. just basically screenshots to show the user that we are communicating the same ideas. Create a worksheet for each "View" or screen you need to show. Client's usually only care how "pretty" an application looks vs does it work right.
This also is a benefit as you can include more non-technical users in the prototyping process, since most are used to excel. I can send you an example and the finished production web application, if seeing is believing. I personally learn best by example.
And to your post where you wrote...
I mean, if we tell the client to wait till we have a working demo (by ASP.Net MVC) we may lose the client and the whole project opportunity.
They need to have their expectations adjusted and managed. A lot of bad development has been done quickly over the years, which makes client's ask questions like "Bob did it in 1 hour'. To that I say, you can either have a lousy project fast, that you have to constantly duct tape or a well thought out and well written project that will only need to be enhanced as Bus Reqs change
I think the answer is obvious: use whichever you think makes you faster. There's no point in using MVC if you are faster in WebForms. Especially since this is for a throw-away demo.

Why MVC instead of good old ASP.NET? Still not grasping why I should go this route?

I know this question has been asked before and I read all the answers but they still don't give me the answers I am looking for. I need something concrete. I volunteered to give a presentation on MVC to other developers in our group which forces me to learn it. The big question everyone has is: "What can MVC bring to the table that we can't do in asp.net or MVC can do faster. I have just gone through Nerd Dinner and actually created a complete website that sort of mimics Nerd Dinner. But as great a job that Scott Guthrie did on it, there are big gaps that aren't answered such as, how do I throw a textbox on the listing page with a button and do a simple search. In asp.net, I would throw a textbox, button and grid on the page and bind it to a sproc and away I go. What is the equivalent in MVC. I guess I need a really good tutorial on how to use MVC without using Linq-to-Sql.
I know I am sort of babbling on about this but it is a very serious question that still seems to go unanswered.
On a side note, the View page of MVC brings back nightmares of classic asp with all the in-line code that we got away from way back when with code behind pages. Yes, MVC has Controller and Model classes which are great but I still don't like the classic asp tags in the html.
Help me out here, I really like the concept of MVC and want it to be successful but I need more!
how do I throw a textbox on the listing page with a button and do a simple search. In asp.net, I would throw a textbox, button and grid on the page and bind it to a sproc and away I go
That's exactly the biggest problem behind "classic" ASP.NET aka WebForms.
You shouldn't be thinking in terms of pages, buttons and events.
You should learn the basics of how web works. Then you'd understand that the web speaks in terms of HTTP protocol, its commands GET, POST and others. Presentation is HTML, CSS and the Document Object Model which is where JavaScript comes into play. And there are in fact no pages, an url is just a pointer to a resource which is not necessarily mapped to a physical file (.html or .aspx) on the server.
the View page of MVC brings back nightmares of classic asp with all the in-line code that we got away from way back when with code behind pages.
I also came to MVC after staying with WebForms and I discovered I like the inline code very much. It makes the view structure very clear, which cannot be said about the coupling of static markup (aspx) + manipulating server controls in code-behind. The latter is actually a nightmare - your code is generating the markup output but you don't see where and how.
What can MVC bring to the table that we can't do in asp.net or MVC can do faster
It removes the ugly stateful abstraction which WebForms gave us. You're now back where it started. What you have now is:
Option to separate your presentation part (views) from your application logic. Before there was all mixed together, code-behind talking to the database, calling other services, modifying the markup. It was mess. It resulted in lots of serious applications written but hardly maintainable any more.
Ability to automatically test your application logic. With WebForms and code-behind, how would you invoke a certain scenario? You'd use tools like Selenium to mimic user activities. Now, when your views are just a passive presentation layer, you don't have this problem any more. You test your business logic and model output very easily. Views are there to display the results. If the model got the correct data in a particular scenario, the view will display it correctly. If not then not. Period. No need to test views.
Control over your markup. That is if you care. If you a former Windows developer who doesn't give a damn about HTML documents being valid, being semantically correct and optimized for web engines, then it's of no use to you. I mean, "pages" are sort of displayed, user clicks are processed like in desktop application, what else, right? But if you were interested in all those things, then you'd look at the final markup output and see that it is ugly, with lots of errors, limitations which you simply can't fix. Because it's how controls, buttons, data grids etc. display themselves. An attempt to fix them would require to override markup generation of those controls which is a heavy task. Why don't just drop it and do everything manually?
What MVC takes from the table?
A server-side processing of "control" "events", like in Windows programming. If you're developing a desktop-like application for web medium, like those typical "business" software with dozens and hundreds of controls to drive you crazy, then MVC will drive you crazy, because you will have to wire each single control individually with JavaScript.
But if you're not developing those kinds of applications (which require certain mental abilities to work with), but developing modern usable software for web, then WebForms would drive you crazy. Sooner or later.
I was also learning MVC in the past few days. My experience is that is provides a much less complicated model of the web.
While WebForms promised that it will make web development very close to Windows development with a complicated event model, controls, and all the stuff.
Why? Because at the time Microsoft's developer base was mostly VB and C++ developers who were thinking in terms of forms, controls, and this provided an easy way for them to begin developing for the web.
What MVC provides is more control over the underlying protocol and more control over the HTML you output.
Plus, they give you ASP.NET routing built-in, so your URLs will also look and feel much better.
An example: StackOverflow was built using ASP.NET MVC.
Your example:
how do I throw a textbox on the
listing page with a button and do a
simple search. In asp.net, I would
throw a textbox, button and grid on
the page and bind it to a sproc and
away I go.
You create an Action for it in the current Controller, throw a form on the page with Html.BeginForm which points to that action (remember, with MVC, you can have multiple forms on pages), throw a textbox and a submit button in it.
Then, according to your taste, you can either create a separate view for the search results, or reuse the existing view. The new action can be named the same as the old one, with [HttpPost] on it (or [HttpGet] if you prefer that), so the URL won't confuse the users more. You can then call your SPROC in your action and you are good to go.
(All this accomplishable in a matter of minutes.)
The other thing I like about MVC is that it is basically VERY EASY to create CRUD operations with it. (Like NerdDinner.)
VS generates 80% of the code required for your views, which then you can customise very easily.
I recommend you reading the whole book and not only the NerdDinner free episode, it gives you a very good picture about the technology.
The bulky Behind code is one the biggest issue with Webform. The RAD approach is good to create project faster but the growing bulky behind code is not maintainable , reusable and testable. There are 5 problems which MVC resolves of WebForm.
Problem 1 :- Webform was a View based solution for Action based requirement
Problem 2:- Tight coupling between behind code and view
Problem 3:- HTML is not the only response type in Webform it was not flexible
Problem 4:- Flexible Combination of view and data not possible with webforms
Problem 5:- Behind code was a heavy bulky class which can not be instantiated.
All the above points has been explained in this codeproject article http://www.codeproject.com/Articles/821275/Why-ASP-NET-MVC-ASP-NET-MVC-vs-ASP-NET-webforms
The following article got me started with MVC
ASP.NET web forms aren't going
anywhere. As much as I love ASP.NET
MVC, it is not the end-all-be-all
one-size-fits-all solution to web
development. Both of these approaches
have their rightful place in a web
developer's toolbox and it's important
to recognize their strengths and
weaknesses. In general, the ASP.NET
MVC framework tends to sacrafice
ease-of-use (e.g. viewstate,
validation, etc.) in order give
developers tighter control over the
reins. This can be a great thing, but
only if you take advantage of it.
Otherwise it can just as easily be a
hindrance.
With that in mind, I have developed a
quick metric to determine if ASP.NET
MVC is right for you. The way I see
it, there are three primary reasons a
developer should choose the ASP.NET
MVC framework over ASP.NET web forms.
If none of these reasons are
compelling to you, then you should
stick with ASP.NET web forms:
To Unit Test This, in my opinion, is
the most compelling reason to use
ASP.NET MVC. When it comes to unit
testing, ASP.NET MVC simply blows
ASP.NET web forms out of the water.
It's not even close. Whereas ASP.NET
web forms requires you to jump through
all sorts of hoops to test around the
page event lifecycle, the ASP.NET MVC
framework practically begs to be
tested. There are interfaces
everywhere screaming "mock me!".
There's a reason why the biggest
ASP.NET MVC supporters also tend to be
TDD proponents; it's because ASP.NET
MVC actually allows for TDD.
Personally, I think this is where all
the zeal comes from. Simply put: it's
really, really hard to do TDD with
ASP.NET web forms and really, really
easy to do it in ASP.NET MVC.
To Gain Control and Extensibility As
pointed out in the comments, ASP.NET
MVC gives you more control and
extensibility options than ASP.NET web
forms. You get complete control over
the page request lifecycle and the
ability to substitute out several key
pieces of the framework (e.g. view
engine, routing, etc.), none of which
is possible with ASP.NET web forms.
In addition to this, you also gain
full control over the rendered HTML.
In general, the rendered HTML from
ASP.NET web forms applications is
atrocious. The web controls it
utilizes generate garbage ids and
hidden fields galore that not only
hamper the performance of a site, but
also make CSS styling and Javascript
development a pain. ASP.NET MVC
forces you to be more in tune with
your HTML. There aren't any repeaters
or datagrids that magically generate
markup for you. There aren't any
hidden fields to persist state for
you. It's just you, the HTML, and a
few extension methods (which you don't
even have to use).
To Learn Something New In other words,
"because you feel like it". This was
actually why I started using ASP.NET
MVC. It never hurts to look at how
you're approaching development from
another angle.
I should also point out that learning
ASP.NET MVC is incredibly engaging
process since the ASP.NET MVC
framework team has been so interactive
in the process. I think a large part
of the appeal of ASP.NET MVC is that
the community's input is not only
being taken into consideration, it is
actively being sought after. The
framework has sparked so many
discussions and debates over best
practices that simply following along
introduces you to concepts you might
previously have been unaware of. I
would actually recommend learning the
ASP.NET MVC framework for this reason
alone. The threads on TDD, BDD, ORM,
AJAX, etc. you stumble across during
the learning process are worth it.
So there you have it. Aside from
those three, I can't think of any
other reasons why a developer would
learn ASP.NET MVC. Maybe this is why
the adoption rate isn't nearly as high
as we think it should be. The
incentive for using the framework
essentially boils down to unit
testing, control/extensibility, and
boredom/curiosity. Good reasons, to
be sure, but hardly game breakers for
the vast majority of developers out
there.
Control over the HTML output - is one thing. All those fancy controls SERIOUSLY SUCK from a SEO point of view.
Plus for COMPLEX forms, the ASP.NET state model is hell, too ;)
Anyhow, an example is your search box... it sucks ;)
I would use MVC like this:
Search is a URL:
/search/keyword
or
/search/keyword/pagenr (like /search/programming/5
Good thing is: I can easily have search results spidered by google - some sites I Know get most hits from something like that.
Is it harder to program than asp.net - depends whether you want efficient HTML or not. THe control model from ASP.NET does not lead to lean defined HTML somehow.
Besides that - MVC is a lot more testable. Unit testing a classical HTML site is pretty impossible, the decoupled model of MVC makes that easier.
I don't come from a Microsoft background, so I might be missing something strictly related to ASP.NET but MVC isn't something different than ASP.NET. MVC, or model-view-controller, is an architectural principal in software design that isn't strictly for the web. Graphical user interface applications commonly use this model.
Anyway, your question is dealing with the "why". The search listing page is a good example to start with. With MVC, you can use templates to only modify the visual aspects of the search (the view). You can add buttons and format what the controller gives you without having to make changes to the controller itself. Similarly, with a view you can change the logic of what is "given" to the view without actually changing the view. Finally, you can go from a relational database to an XML database and without having to worry about changing any of the other aspects of your program. The logic is separated cleanly and this pattern fits many use-cases.
I would highly recommend seeing the Wikipedia article on MVC. It may be easier to understand using a graphical user interface (GUI) example instead of a simple web based example.
Ryan
MVC is considered as an alternative to good old asp.net, not the next step. IMHO MVC has a clear advantage if you want to write unit tests for your pages.
But I don't agree that MVC adds anything to classic asp.net in the name of performance, code quality or productivity. You can achieve same performance with asp.net by shutting down viewstate when not necessary or you can be more in control of HTML output by using lightweight server controls. (Repeater instead of DataGrid for example.)

Converting ASP.NET web site to MVC2

I have my existing web site developed using ASP.NET.
It's college management system. Now I need to redevelop it on MVC2.
What all changes do I need to do?
I am little bit aware of MVC and have done some exercises also.
Thing I know is I can keep my database intact but there will be massive changes at other places.
WHat will be the better way to minimize the changes?
MVC is a very different concept from event-oriented WebForms. There's good chance you will have to redo the frontend completely.
Try to find out if there is anything resembling data access layer and the business logic layer. If so, you can keep them (at least partially) and reuse their methods.
However, if the current application is not well structured and looks like a giant code blurb (with no layers, parts of the code talking to any other part at will, page methods going directly to the database etc.) it may have to be redone entirely.
If the application is now heavily relies on data-bound controls, you're screwed. You will have to recreate a lot of functionality by hand.
You should be able to refactor the middle tier (if you're using a multi-tier approach) into controller/model while keeping the UI intact. Once you've done that, throw away your UI and write a proper View. Try using LINQ-To-Sql for the backend.

Building ASP.NET application - Best Practices

We are building an ASP.NET application and would like to follow the best practices. Some of the best practices are:
Server side Code:
Use catch blocks to trap & log low level errors too.
Use Cache objects to populate dropdowns etc. where we won’t expect the changes in the underlying data/database.
In case of error logging framework, provide emailing alerts along with logging the errors.
HTML code:
- Don’t write inline CSS.
- Place the JavaScript code (If needed by the page) at the end of the page unless the page needs it for load time actions.
Now coming to the point, Would you please share these best practice points if you have a comprehensive list of them already?
Some of the best practices that I've learned over time and written up for use at my company...many are mainly applicable to WebForms and not MVC.
Don't write .NET code directly in
your ASPX markup (unless it is for
databinding, i.e. Evals). If you
have a code behind, this puts code
for a page in more than one place and
makes the code less manageable. Put
all .NET code in your code-behind.
SessionPageStatePersister can be used in conjunction with ViewState
to make ViewState useful without
increasing page sizes. Overriding
the Page's PageStatePersister with a
new SessionPageStatePersister will
store all ViewState data in memory,
and will only store an encrypted key
on the client side.
Create a BasePage that your pages can inherit from in order to
reuse common code between pages.
Create a MasterPage for your pages
for visual inheritance. Pages with
vastly different visual styles should
use a different MasterPage.
Create an enum of page parameter key names on each WebForm
that are passed in via the URL, to
setup strongly-typed page parameters.
This prevents the need for hard-coded
page parameter key strings and their
probable mis-typing, as well as
allowing strongly-typed parameter
access from other pages.
Make use of the ASP.NET Cache in order to cache frequently used
information from your database.
Build (or reuse from another project)
a generic caching layer that will
wrap the ASP.NET Cache.
Wrap ViewState objects with Properties on your Pages to avoid
development mistakes in spelling,
etc. when referencing items from the
ViewState collection.
Avoid putting large objects and object graphs in ViewState, use it mainly for storing IDs or very simple DTO objects.
Wrap the ASP.NET Session with a SessionManager to avoid development
mistakes in spelling, etc. when
referencing items from Session.
Make extensive use of the applicationSettings key/value
configuration values in the
web.config - wrap the
Configuration.ApplicationSettings
with a class that can be used to
easily retrieve configuration
settings without having to remember
the keys from the web.config.
Avoid the easiness of setting display properties on your UI
controls, instead use CSS styles and
classes - this will make your styles
more manageable.
Create UserControls in your application in order to reuse common
UI functionality throughout your
pages. For example, if a drop down
list containing a collection of
categories will be used in many
places in the site - create a
CategoryPicker control that will data
bind itself when the page is loaded.
Use Properties on your UserControls to setup things like
default values, different displays
between pages, etc. Value type
properties can be defined on your
UserControls and then be set in your
ASP.NET markup by using class level
properties on UserControls.
Make use of the ASP.NET validation controls to perform simple
validations, or use the
CustomValidator to perform complex
validations.
Create an Error handling page that can be redirected to when an
unhandled exception occurs within
your website. The redirection can
occur via the Page_Error event in
your Page, the Application_Error
event in your Global.asax, or within
the section within the
web.config.
When working with pages that use a highly dynamic data driven
display, use the 3rd party (free)
DynamicControlsPlaceholder control to
simplify the code needed to save the
state of dynamically added controls
between postbacks.
Create a base page for all your asp.net pages. This page will derive from System.Web.UI.Page and you may put this in YourApp.Web.UI. Let all your asp.net pages dervice from YourApp.Web.UI.Page class. This can reduce lot of pain.
Use Application_OnError handler to gracefully handle any error or exception. You should log the critical exception and send the details of the exception along with date-time and IP of client to the admin email id. Yes ELMAH is sure way to go.
Use ASP.NET Themes. Many developers don't use it. Do use them - they are a great deal.
Use MembershipProvider and RoleProvider. And Never use inbuilt ProfileProvider - They store everything in plain strings. It will drastically slow-down the performance while performing R/W
Use Firebug for client-side debugging. Try to follow YSlow standards for web-applications. Use YSlow extension for FireBug.
Use jQuery for client-scripting.
Never store User Authentication information in session or don't use sessions to judge if user is logged on. Store only minimum necessary information in sessions.
Have a look at PostSharp. Can improve maintainability of your code and make you more productive.
Never ever Deploy asp.net application under debug configuration on production. Find out here what scottgu has to say about this.
User Web Deployment projects. It can transform web.config sections and replace with production server setings. It will merge all compiled code-behind classes into one single assembly which is a great deal.
Use Cookie-less domains to serve static resources like images, scripts, styles etc. Each client request is sent along with whole bunch of cookies, you don't need cookies while serving pictures or scripts. So host those resources on a cookie-less domain.
Minify scripts, stylesheets and HTML response from the server. Removing unnecessary line-breaks and white-spaces can improve the time-to-load and bandwidth optimization.
Forms:
Set Page.Form.DefaultFocus and Page.Form.DefaultButton to improve user experience
Check Page.IsValid in your Save button handler before proceeding.
General:
Understand and implement the techniques found in the article "TRULY Understanding ViewState"
Use Page.IsPostBack in your page events to stop code from running unnecessarily.
Use hyperlinks instead of posting and using Response.Redirect whenever possible.
a. Understand and use the second parameter of Response.Redirect (it "Indicates whether execution of the current page should terminate")
Use the Page Lifecycle properly.
Use the Per-Request cache (HttpContext.Items) instead of Cache where it makes sense.
Web.Config:
Deploy with <compilation debug="false">
Register your controls at the web.config level instead of the page level (i.e. #Register).
Themes:
When using Themes, put your static images in the Theme as well.
a. Don't link to the images directly from your markup, link to them from a skin file or css file in your Theme instead.
ex: <asp:Image SkinID="MyImage" runat="server" ImageUrl="Images/myImage.gif" />
I don't think try/catch blocks are always appropriate for low-level methods. You want to catch (and log/alert, even better!) any errors before they get to the user, of course. But it is often better for a low-level method to just lets its errors get raised up to a higher level. The problem I have seen with low-level error trapping is that it often lets a larger operation continue, but then a result that is not quite correct gets presented to the user or saved to the database, and in the long run it's much more difficult to fix. It's also just a lot of extra clutter in your code to put a try/catch at every level if you're not going to "do anything" with the error until it's raised up to a higher level.
Here are some similar questions that may help you.
.NET best practices?
Best way to learn .NET/OOP best practices?
This should probably be community wiki as well.
I would recommend a couple of books if you are interested in pursuing a journey to become a better, more productive developer. These books are language agnostic and as you can see by the user reviews, very very helpful.
Code Complete 2
Pragmatic Programmer
If you are looking for a .NET specific book, you may appreciate the following book:
Microsoft Application Architecture Guide [available online for free outside of print format]
ASP.NET
If you don't use Session state, don't
forget to turn off it.
Use Server.Transfer instead of Response.Redirect if possible.
Set expiration parameter in IIS.
Use GZip to compress the text files.
Use Server-Side and Client-Side validation together.
Use Url Rewriter or Routing to make friendly url for SEO.
Design
Write each class and its properties
of your CSS file in the same line. (To decrease the file size)
Use CSS Sprites. (To decrease request)

Resources