<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gary Pretty's Blog &#187; MVC</title>
	<atom:link href="http://blog.garypretty.co.uk/index.php/tag/mvc/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.garypretty.co.uk</link>
	<description>.Net Development &#38; General Tech Related News</description>
	<lastBuildDate>Sat, 04 Feb 2012 00:32:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Multi-Select List Box in ASP.NET MVC</title>
		<link>http://blog.garypretty.co.uk/index.php/2010/02/26/multi-select-list-box-in-asp-net-mvc/</link>
		<comments>http://blog.garypretty.co.uk/index.php/2010/02/26/multi-select-list-box-in-asp-net-mvc/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 17:13:57 +0000</pubDate>
		<dc:creator>Gary Pretty</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity Fraemwork]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.garypretty.co.uk/?p=245</guid>
		<description><![CDATA[Recently I have been working on an MVC site using the Entity Framework.  I have some related entities in my EF model, as show below in the form of &#8220;Reader&#8221; and &#8220;Category&#8221;, and the relationship between them, i.e. many to many. When it came to proucing a view and action to perofrm the Create Reader &#8230; </p><p><a class="more-link block-button" href="http://blog.garypretty.co.uk/index.php/2010/02/26/multi-select-list-box-in-asp-net-mvc/">Continue reading &#187;</a>]]></description>
			<content:encoded><![CDATA[<p>Recently I have been working on an MVC site using the Entity Framework. </p>
<p style="text-align: center;">I have some related entities in my EF model, as show below in the form of &#8220;Reader&#8221; and &#8220;Category&#8221;, and the relationship between them, i.e. many to many.<br />
<img class="aligncenter size-medium wp-image-248" style="margin: 10px; border: black 1px solid;" title="EF Model" src="http://blog.garypretty.co.uk/wp-content/model-283x300.png" alt="" width="283" height="300" /></p>
<p>When it came to proucing a view and action to perofrm the Create Reader action, I was somewhat puzzled as to how I could allow the user to select one or more categories for a reader. </p>
<p>I started by having a view model that contained a list of all possible categories and then looping around these in my view and writing a check box out for each one.  When the form was submitted I looked through the form collection to find if any of the category check boxes had been selected.  I didn&#8217;t like this one bit and so I set out to find a cleaner way of carrying it out.</p>
<p>After some (quite a lot actually) searching, I stumbled accross the MultiSelectList type, which I could use in my ViewModel and then allow the default model binding to step in and do the leg work for me <img src='http://blog.garypretty.co.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Great!</p>
<p>So, I created a view model, a simplified version of which you can see below;</p>
<blockquote><p>    public class ReaderCreateViewModel : CustomViewModelBase<br />
    {</p>
<p>        public ReaderCreateViewModel()<br />
        {<br />
            ReaderDetails = new Reader();<br />
            CategoriesList = GetCategories(null);<br />
        }</p>
<p>        public Reader ReaderDetails { get; set; }<br />
        public MultiSelectList CategoriesList { get; private set; }<br />
        public int[] SelectedCategories { get; set; }</p>
<p>        public MultiSelectList GetCategories(int[] selectedValues)<br />
        {<br />
            var te = new myEntities();<br />
            List&lt;Category&gt; categories = te.Categories.ToList();<br />
            return new MultiSelectList(categories, &#8220;id&#8221;, &#8220;Name&#8221;, selectedValues);<br />
        }<br />
    }</p></blockquote>
<p> As you can see from the code above, the view model contains my Reader entity, a list of type MultiSelectList, which is a list of available categories and an array of integers which represent the Id of any selected Categories.</p>
<p>Then to add a listbox to my view that will bind the MultiSelectList, I simply insert the following into my view.</p>
<blockquote><p>            &lt;p&gt;<br />
             &lt;label for=&#8221;SelectedCategories&#8221;&gt;Categories:&lt;/label&gt;<br />
        &lt;%= Html.ListBox(&#8220;SelectedCategories&#8221;, Model.CategoriesList) %&gt;<br />
            &lt;/p&gt;</p></blockquote>
<p>Finally in my controller, I can simply check the SelectedItems object in my model for any selected Ids and add them to the Reader Categories list like this;</p>
<blockquote><p>            if (model.SelectedCategories != null)<br />
            {<br />
                foreach (var selectedCat in model.SelectedCategories)<br />
                {<br />
                    int selectedCatId = selectedCat;<br />
                    Category category = DataContext.Categories.Where(c =&gt; c.id                  == selectedCatId).FirstOrDefault();<br />
                    reader.Categories.Add(category);<br />
                }<br />
            }</p></blockquote>
<p>And that&#8217;s it.  Now there is probably a much better way of doing all or some of the above, but this worked perfectly for me when I needed it, so I hope it helps someone else out as well.  The final multi-select list box looked something like this;</p>
<p><a href="http://blog.garypretty.co.uk/wp-content/listbox.bmp"><img class="aligncenter size-full wp-image-250" title="listbox" src="http://blog.garypretty.co.uk/wp-content/listbox.bmp" alt="" /></a></p>

<!-- start wp-tags-to-technorati 1.02 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/ASP.NET+MVC' rel='tag' target='_self'>ASP.NET MVC</a>, <a class='technorati-link' href='http://technorati.com/tag/Entity+Framework' rel='tag' target='_self'>Entity Framework</a>, <a class='technorati-link' href='http://technorati.com/tag/MVC' rel='tag' target='_self'>MVC</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://blog.garypretty.co.uk/index.php/2010/02/26/multi-select-list-box-in-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

