ASP.NET MVC: MultiSelectListBox without selection

Alright, now that was one hell of a mystery. For some odd reason my MultiSelectListBox didn’t show the selected items like it should.


The case was very simple, and easily reproducible too. Start of in VS2008 with a new MVC Web Application, open up the HomeController class and change it’s code to this (only italic code was added):


    public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";

var dic = new Dictionary<string, string>();
dic.Add("1", "First thing");
dic.Add("2", "Second thing");
dic.Add("3", "Third thing");

var sel = new ArrayList();
sel.Add("2");

ViewData["multiselect"] = new MultiSelectList( dic, "Key", "Value", sel);

return View();
}

public ActionResult About()
{
return View();
}
}

As you can see, this adds a MultiSelectList to the ViewData object. It conatins a dictionary with 3 items. In addition an ArrayList with 1 string is passed, to represent the selected items. Now, open up Home\Index.aspx and add the following code somewhere in the HTML-Body:


<%= Html.ListBox("multiselect", ViewData["multiselect"] as MultiSelectList)%>

When running the application I expect the homepage to show up with the second item in the select list selected, but in stead it showsno selection at all:


image


It took quite some puzzling, but it the problem turned out to be caused by the element in ViewData having the same name as the Id for the control. If you change the line in Home\Index.aspx as follows:


<%= Html.ListBox("someMultiselect", ViewData["multiselect"] as MultiSelectList)%>

The selection will finally show:


image


Pfff, glad I nailed that one…

LINQ to SQL Connectionstring in web.config

For starters, there’s probably dozens of places on the web already, with a solution for this very same issue, but here’s mine anyway.

The issue is this: when creating a website in ASP.NET using LINQ to SQL, you’ve probably guessed it would be a good idea to put the connectionstring in web.config. Especially since there’s a special section for them there.

However, when you create a LINQ to SQL Databaclasses (.dbml) file and drag your tables on it, it’s automatically configured to use the database you dragged the tables from.

And it’s pretty easy to solve too. First, we want to get the connectionstring out of the .dbml file. To do this, open the .dbml file in the designer and change it’s data-properties to match this:

image

Then, create a new partial class for the generated DataContext class with only a default constructor in it. This default constructor will pass the connectionstring from web.config to the constructor if it’s base class, and you’re al set:

public partial class MyDataContext{
    public MyDataContext()
        : base(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString,mappingSource)
    {
    }
}


This way, you can always regenerate your dataclasses without having to remember to change



use the right connectstring.



Have Fun!

ASP.NET: Leaping from Webforms to MVC – part 2

Alright, some time has passed since my previous post on this matter. And I must say, I’m not getting more enthusiastic on ASP.NET MVC. Not that it’s not good or anything, it just solves some problems I wasn’t experiencing (more on that here). The main issue I’m running into is that my pages are somewhat dynamic. That means, based on several conditions, the form displays in one of several ways (for example: based on a property of an object a field displays as either a label or a textbox).

At this point I’m typing a whole lot of crappy code in my HTML within <% %> tags. It just feels soooo retro…

retro code

Unable to save changes to a table (SQL2008)

Don’t you love it when you have just a tiny task and get surprised by something you never heard of? I don’t but still it happens…

So, I need to add a column to a table in my local SQL2008 database. Open up SQL Server Management Studio, navigate to the table, right click, choose Design Table, add the column and click the diskette icon (how long will that still be around?). Easy as that, except that I get punched in the face by this message:

Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.

Never heard of that. I’m pretty sure the table can be dropped and re-created, so I’ll start off searching for the option “Prevent saving changes that require the table to be re-created”.

But I DO love it when you find an option you’re looking for at first try. Tools, Options, Designers, Table and Database designers:

image

ASP.NET: Leaping from Webforms to MVC

Ever since late 2007 (I think Thinking) I’ve been reading quite a bit on the ASP.NET MVC framework. Even did some playing around here and there but never got to use it on a project. Until last week that is. I’m now working on a website that’s built entirely on the ASP.NET MVC framework. And of course, working on a project things are just a tad different from playing around a bit.

So, what is it that makes working with the MVC Framework so much different from Webforms? Well, let’s just put a small list here of some of the things I ran into. Needless to say that this is not a complete list, nor is it intended to be…

Where are the servercontrols?

Well, errrr, they’re gone. You don’t have them. You’re writing good old HTML again yourself. Of course, the advantage here is that you gain a lot of control over the HTML of your website. But, of course, no Servercontrols means “no events”. You even need to pull a trick to make a DropDownList autopostback (more on that here)…

Only one <Form> in a page?

Alright, an advantage of the MVC Framework. Every now and then I tend to run into this situation where I need some part of a page to submit to a different URL. In ASP.NET you need to use javascript Nerd to change the Action of the Form before it’s submitted. Or at least, that’s one approach of numerous you could choose from…

In ASP.NET MVC you can easily have different forms on a single page. Love that partRed Lips.

More to come

… as I experience. I decided to post and update this one along the way.

Autopostback DropDownList with ASP.NET MVC

PropertiesPaneDidn’t you love the days back when you could just open up the properties tab for your DropDownList in ASP.NET and set the AutoPostBack Property to True? You could even write code in your codebehind class to handle the event properly. Cool, right? Hot


But these are the days of the ASP.NET MVC framework, so everything’s different now. Well, of course I’m being a bit sarcastic Sarcastic here and there are a lot of advantages too to the MVC Framework, but still it requires more work to achieve things-that-used-to-be-simple.


Anyway, back to the AutoPostBack of the DropDownList. First, of course, you need to have a DropDownList on your page:


<select id='dropDown' name='dropDown'>
<option value="1" selected="selected">Option 1</option>
<option value="2">Option 2</option>
</select>

Note that this control needs to be within your Form otherwise it’s values will not be submitted of course…


When you have the control, you’ll need to make it submit the Form it’s in. I chose to do so with jQuery, but you could do it with plain javascript too:


<script type='text/javascript'\> 

  $('#dropDown').change(function () {
$(this).parents('form').submit();
});

</script>

For those of you not fully up to speed with jQuery: this code finds the element named “dropDown” and adds a handler to the onChange event of it. The handler first finds the parent of the DropDownList with elementname “form”, and submits it.


You could also change the action of the form here in the handler if that might be needed, for example to fire a specific controller action for the postback of the DropDownList.