Sunday, October 9, 2011

Model Bind to a Collection

I'm trying to do something like this in this post in the name of figuring out how to model bind collections. My approach is more ghetto. I have three objects:

using System.Collections.Generic;

namespace MvcApplication.Models

{

   public class Foo

   {

      public string Whatever { get; set; }

      public List<Bar> SomeCollection { get; set; }

   }

}

 
 

namespace MvcApplication.Models

{

   public class Bar

   {

      public int Number { get; set; }

   }

}

 
 

namespace MvcApplication.Models

{

   public class Baz

   {

   public string Question { get; set; }

   }

}

 
 

Alright, here is a view that uses a list of Baz as a its model and will bind to a Foo:

@using MvcApplication.Models

@model List<Baz>

@{

ViewBag.Title = "Home Page";

Int32 counter = 0;

}

<h2>@ViewBag.Message</h2>

<form method="post" action="/home/about/">

<input type="test" name="Whatever" />

@foreach(Baz baz in Model)

{

   <br/>

   <br/>

   @baz.Question

   <table>

      <tr>

         <td>0</td>

         <td>1</td>

         <td>2</td>

         <td>3</td>

         <td>4</td>

         <td>5</td>

         <td>6</td>

      </tr>

      <tr>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="0" />

         </td>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="1" />

         </td>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="2" />

         </td>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="3" />

         </td>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="4" />

         </td>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="5" />

         </td>

         <td>

            <input type="radio" name="SomeCollection[@counter].Number" value="6" />

         </td>

      </tr>

   </table>

   counter++;

}

<input type="submit" value="submit" />

</form>

No comments:

Post a Comment