2

The code below is taken from the instructors Edit view of this tutorial: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/updating-related-data-with-the-entity-framework-in-an-asp-net-mvc-application

    <div class="editor-field">
        <table style="width: 100%">
            <tr>
                @{
                    int cnt = 0;
                    List<ContosoUniversity.ViewModels.AssignedCourseData> courses = ViewBag.Courses;

                    foreach (var course in courses) {
                        if (cnt++ % 3 == 0) {
                            @:  </tr> <tr> 
                        }
                        @: <td> 
                            <input type="checkbox" 
                                   name="selectedCourses" 
                                   value="@course.CourseID" 
                                   @(Html.Raw(course.Assigned ? "checked=\"checked\"" : "")) /> 
                            @course.CourseID @:&nbsp; @course.Title
                        @:</td>
                    }
                    @: </tr>
                }
        </table>
    </div>

This code renders the course checkboxes below:

Edit View http://i2.asp.net/media/2577999/Windows-Live-Writer_Updating-Re.NET-MVC-Application-6-of-10h_AEF7_Instructor_edit_page_with_courses_1.png

It would be much more elegant to achieve the same result using helper methods and an editor template, right? e.g.:

View

    <div class="editor-field">
        <table style="width: 100%">
            @Html.EditorFor(model => model.courses)
        </table>
    </div>

Editor Template

@model AssignedCourseData
@using ContosoUniversity.ViewModels

<tr>
<td>
    @Html.HiddenFor(model => model.CourseID)    
    @Html.CheckBoxFor(model => model.Assigned)
    @Html.DisplayFor(model => model.CourseName)
</td>
</tr>

Except that this doesn't render the checkboxes as a 3-column table. Can anybody advise how to do so?

user1405195
  • 1,667
  • 4
  • 22
  • 35

0 Answers0