ASPNET MVC
There are 15 entries for the tag ASPNET MVC
Monday, January 23, 2012 3:58 PM | Comments

By using the the simple SelectorAttribute and EditorTemplate described in this post, you will get rich support the following very common scenarios (and flip between the various modes with ease): Single selection from a Drop Down Single selection from Radio Buttons Multiple selection from Check Boxes Multiple selection from a List Box Read-only mode combines multiple values into a comma-delimited string The Canonical example Say you’re inserting a new Product and need to set the CategoryId property. You make a simple input Model wanting to use EditorFor, but CategoryId gets rendered as a useless textbox. The challenge is: Retrieving the list of categories to present to the user Keeping the selected item(s) in sync with the...

Friday, January 13, 2012 2:40 PM | Comments

Many ASP.NET applications utilize the System.Web.Caching.Cache in some way. While it offers a pretty simple Dictionary-like API that your app can start using immediately, I typically create a combined “tell-don’t-ask” wrapper around it – which has some additional architectural benefits as well. Out of the box concerns A very common usage of the Cache API can be seen below, but there are a few initial problems I have with it: Ugly, non-generic casting Manual null checks Duplicating the string for the key Lots of implementation details sprinkled around No out of box way to scope the cache. For example, cache a unique copy of the item for each User   public ActionResult Bad() { var firstVisit = HttpContext.Cache.Get("FirstVisit") as DateTime?; ...

Tuesday, January 10, 2012 10:12 AM | Comments

Many line-of-business applications contain dozens of forms similar to the following, each field consisting of a few common characteristics: A Label with the name of the field The field editor itself Asterisks and special styling for required fields A tooltip that can be hovered for a detailed description of the field Validation messages if the input is incorrect To achieve this, we can create the following Model public class ProductInput { [HiddenInput(DisplayValue = false)] public int Id { get; set; } [Required] public string Name { get; set; } [Required] [Display(Description = "A brief description of the product")] [DataType(DataType.MultilineText)] public string...

Sunday, November 27, 2011 1:32 PM | Comments

This post is an update to my original ASP.NET MVC Recursive TreeView Helper from almost 3 years ago. Oddly enough it’s still a high-traffic post and has close to 50 comments asking for an update or a complete solution to download. I figured if I was going to do that, I might as well give the API a much-needed facelift and pop it on NuGet. What is it? Given the following self-referencing hierarchal model… public class TreeViewLocation { public TreeViewLocation() { ChildLocations = new HashSet<TreeViewLocation>(); } public int Id { get; set; } public string Name { get; set; } public virtual int? ParentLocationId { get; set; } public virtual ICollection<TreeViewLocation> ChildLocations...

Tuesday, August 16, 2011 12:07 PM | Comments

The default Model Binder in ASP.NET MVC works fine for most cases. Most of you have probably registered custom binders with it plenty of times. ModelBinders.Binders.Add(typeof(ILoadProvider), new LoadProviderModelBinder()); The issue is that that it’s limited to binding the exact type you add to its dictionary. The ILoadProvider registered above will invoke my LoadProviderModelBinder as long as the controller action parameter is of type ILoadProvider. But what if you have a type that derives from ILoadProvider and still want your custom binding to occur? Thankfully this is very simple in ASP.NET MVC 3. It comes with a new extensibility point, IModelBinderProvider, and works just like the other providers. public interface IModelBinderProvider { IModelBinder GetBinder(Type modelType); } InheritanceAwareModelBinderProvider With this interface, we are able to create a very simple InheritanceAwareModelBinderProvider. /// <summary> /// Adds inheritance support when registering model binders. /// Any model binders added here will be invoked if the Type being bound inherits...

Wednesday, March 2, 2011 11:59 PM | Comments

Last week I wrote a tutorial on Progressive enhancement with ASP.NET MVC 3 and jQuery. It might be a good idea to skim it if you aren’t already familiar with some of the concepts. A commenter on the last article posed a great question which sparked some improvements to the original code. Thanks for the suggestion! Quick Recap As a quick recap, our goal is to build a Contact Us form that works perfectly on all browsers, but offers an enhanced experience for modern browsers with JavaScript enabled. JavaScript enabled As you can see when a user visits our site with JavaScript enabled and clicks on the Contact Us link, they are presented with a nice jQuery UI dialog window. They can fill in the form and get a nice confirmation message inside the dialog, and finally close it without ever leaving...

Tuesday, February 22, 2011 11:30 PM | Comments

Progressive enhancement is a strategy for web design that emphasizes accessibility, semantic HTML markup, and external stylesheet and scripting technologies. Progressive enhancement uses web technologies in a layered fashion that allows everyone to access the basic content and functionality of a web page, using any browser or Internet connection, while also providing those with better bandwidth or more advanced browser software an enhanced version of the page. Now that it’s 2011 I hope more .NET web developers really start to take progressive enhancement seriously. Sure many ASP.NET devs work on internal LOB apps and can enforce javascript requirements, but if you’re working on an internet-facing site I encourage you to take advantage of the many PE/unobtrusive javascript techniques we have available these days, especially in MVC 3.   update 3/2/2011 Per a suggestion from a commenter I have written a followup article...

Tuesday, February 15, 2011 9:27 PM | Comments

At PDC'10 last year Microsoft showed their upcoming solution for sharing assemblies between different platforms (Windows Phone, Silverlight, and .NET) – dubbed Portable Library Projects. The release date is said to be H1 2011 so hopefully they are still on track, maybe even to be included in VS 2010 SP1. Until then, we are on our own… Derick Bailey actually prompted this post from his tweet a little bit ago, so I figured I would share the solution I used for Bus Watch Chicago.   step 1: define your entities/model in the client (WP7) project The domain for Bus Watch is public transit, so naturally some of my entities are Routes, Stops, Vehicles, Locations, etc. I define all of these classes in the WP7 project; the Route class can be seen below. The keen eye may have noticed that I defined Route as...

Wednesday, February 17, 2010 3:13 PM | Comments

On the surface, I suppose this is YAMVCVWFC (Yet Another MVC vs. WebForms Comparison). If this topic doesn’t appeal to you, or you’re sick and tired of this discussion then I encourage you to move on. I won’t be offended, promise. This post is here to serve as my living, breathing arguments for fighting for MVC and it will serve to highlight my major gripes with Web Forms. The motivation for this post came from an all-too-familiar IRC chat in #asp.net – for those of you unfamiliar with IRC, it’s a lot like the Twitter of the 90s. Fallacy: Web Forms does everything I need it to (01:29p) <webformsdev> 99.9999999999% of client requests, project requirements, etc etc, can easily and equally be done using webforms or mvc (01:30p) <webformsdev> webforms + jquery = does everything I need (01:30p) <@mattman> getting something...

Saturday, August 15, 2009 7:47 PM | Comments

Note: This article was written for ASP.NET MVC 2 Preview 1 – it may become outdated in future previews. The Html helper in ASP.NET MVC 2 comes with some handy methods called “DisplayFor” and “EditFor” – please see Scott Gu’s article if you are not familiar with these new features. Long story short, they provide an ASP.NET Dynamic Data-like mechanism which uses reflection and templating to render a display form or an edit form. It works great for primitive properties like String, DataTime, Int32, as well as complex types like “Address.” However, as I was playing with them, I came across a rather funny exception (excusable, I suppose, due to the preview state of MVC 2 at the time of this writing).   This exception should never occur. Description: An unhandled exception occurred during the execution of the current web request. Please...

Sunday, February 8, 2009 6:57 AM | Comments

UPDATE 11/27/2011 Please see the updated version of this helper. It now includes a fluent API and can be added to your project very easily with NuGet. Writing a Fluent ASP.NET MVC Recursive TreeView Helper The following helper will make it easy to create a tree view from a recursive self-referencing table. Below you are seeing a tree of “Locations” where each Location can contain X number of child locations. Dependencies  jQuery TreeView Plugin Rendered Tree Table Definition The table itself is extremely simple, each Location has a ParentLocationId which is a relationship to the same table. If the ParentLocationId is null then it is a root location.   Usage Simple <%= Html.TreeView("locations",...

Sunday, November 9, 2008 6:45 AM | Comments

This weekend I started playing with Automated Builds in TFS 2008. Over the next few weeks I am going to setup automated builds for my various projects so I can start running automated integration testing and automated staging releases at certain intervals (nightly, weekly, etc). Unfortunately I hit a snag when I tried building one of my solutions that contained a Web Application Project. After some digging around, I eventually opened up the “Release.txt” log file which can be found in the deployment directory, I found the following error: error MSB4019: The imported project "C:\Program Files\MSBuild\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk. Now I am no where near an expert on MSBuild or the delicacies of .csproj files, so I did my best to poke around...

Monday, February 25, 2008 5:38 AM | Comments

Honestly, I'm not sure if this setting is new to Visual Studio 2008 or not, but I just stumbled onto it. Typically when I'm debugging an ASP.NET application I test one page at a time, by right-clicking on the aspx and selecting View in Browser.   I prefer this method because I can keep the browser open at all times during development and not have to compile the whole site to quickly test something simple like markup changes. The caveat to this however, is that the Visual Studio debugger is not attached to the cassini process, so I cannot hit any break points I have set. For scenarios when I need to debug and step through code, I press the Debug button, wait for the site to compile and spawn a new browser window, and then I manually navigate to the page I want to debug....

Thursday, February 21, 2008 7:11 AM | Comments

The ASP.NET MVC framework ships with a number of Visual Studio project and item templates to ease our development tasks. One of these templates is a UserControl built specifically for the MVC framework. We are going to walkthrough building a re-usable Header control that can be added to the top of related pages (in this specific case, this Control will be added to all Account pages). If you want to get technical, I suppose this may be a good candidate for the new Nested Master Page support in Visual Studio 2008. But for our purposes, this will do just fine. Our end-result will be a control that looks like this, and can be added very easily to our View Pages to provide a consistent navigation element. Create the Control First let's add a new MVC View User Control control to our Views folder in...

Wednesday, February 20, 2008 7:05 AM | Comments

Many of us have probably encountered the need for this on various projects. The scenario is simple, we have optional fields that a user may or may not enter values for, and we would like to hide them from display if they were not filled in. The above screenshot could use some cleaning up. Ideally those fields that contain no data should be hidden from the rendered HTML. Our first attempt might look something like below, but hopefully, after 1 or 2 copy pastes any developer will realize this should be handled differently. Who among us has run into maintaining code looking like this? Ok let's go back to the drawing board. The MVCToolkit comes with many extension methods for the HtmlHelper class that ships with the ASP.NET MVC framework. The Html object is accessible to every MVC Page, and will prove invaluable for generating inputs like  RadioButtonLists, DropDownLists,...