Posts tagged 'Asp.Net Mvc'

NullReferenceException when model binding strings after upgrading from ASP.NET MVC 1 to ASP.NET MVC 2

 

When migrating a site from ASP.NET MVC 1 to ASP.NET MVC 2, you can generally follow the instructions in http://www.asp.net/whitepapers/what-is-new-in-aspnet-mvc#_TOC2, taking note of any breaking changes. This will take you most of the way there, however there are a few undocumented issues which you may uncover if you’re migrating a site with a substantial amount of code.

By default, the ASP.NET MVC 1 model binder would initialize strings to string.Empty whereas ASP.NET MVC 2 will initialize strings as NULL. This is an undocumented breaking change and will be a problem if you have a substantial amount of code relying on the original behavior – code that was previously working in production will start throwing NullReferenceException.

To preserve the original MVC 1 model binder behaviour, consider creating default model binder such as the following:

 

Read More...


ASP.NET MVC - issues with binding a non-sequential list with the default model binder

 

For the ASP.NET MVC default model binder to bind a list successfully, the list must be sequential with unbroken indices.

For the following examples, the server side model will be

public class ItemsModel 
{
    public IList<string> Items { get; set; }
}

Non-sequential form submits when using indexes which don’t start from zero i.e. Item[2], Item[3], etc will result in incomplete form data being loaded by the model binder.

The following will not bind, and will result in the model being NULL:

<input type="text" name="Item[1].Name" value="Item1" />
<input type="text" name="Item[3].Name" value="Item2" />
<input type="text" name="Item[4].Name" value="Item3" />

 

Read More...


ASP.NET MVC - Multiple parameterised form submit buttons without Javascript

 
The current project I’m working on involves a search page with multiple submit buttons in a single HTML form. Each submit button triggers a different behavior while posting all of the form data to the controller. This method is compatible with both IE 6+ and Firefox. It also avoids the IE button bug where button values are not passed on HTTP POST. After discussing a few design options we decided to allow the user to add the desired search parameters via selecting them one by one from a drop down list.
 

Read More...