views:

299

answers:

1

In the MVC RC 2 docs, we find:

Expression-based helpers that render input elements generate correct name attributes when the expression contains an array or collection index. For example, the value of the name attribute rendered by Html.EditorFor(m => m.Orders[i]) for the first order in a list would be Orders[0].

Anyone care to link an example of the C# view code (using a List where the result can bind back to the Model upon post)?

Just as a reference, I use the following code to verify the model binds correctly round trip. It simply shows view that allows change, then displays a view with the edited data upon form submission.

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var myStudents = new List<Student>();

        myStudents.Add(new Student { Name = "Harry" });
        myStudents.Add(new Student { Name = "Tom" });
        myStudents.Add(new Student { Name = "Richard" });
        var myClass = new Classroom {Students = myStudents};

        return View(myClass); // EditorFor()
    }

    [HttpPost]
    public ActionResult Index( Classroom myClass)  
    {
        return View("IndexPost", myClass); // DisplayFor()
    }
A: 

This code:

<% for (int count = 0; count < Model.Students.Count; count++ )
   {                                              %><%= 
      Html.EditorFor(m => m.Students[count])      %><%
   } 
%>

Rendered this output:

<input class="text-box single-line" id="Students_0__Name" name="Students[0].Name" type="text" value="Harry" />
<input class="text-box single-line" id="Students_1__Name" name="Students[1].Name" type="text" value="Tom" />
<input class="text-box single-line" id="Students_2__Name" name="Students[2].Name" type="text" value="Richard" />

And when I posted the content, the display was this (because I have a Student.ascx):

<table>
    <tr><td><span>Harry</span> </td></tr>
    <tr><td><span>Tom</span> </td></tr>
    <tr><td><span>Richard</span> </td></tr>
</table>

But that's it (I think). Next question is how to get rid of those name="" tags.

Dr. Zim