In an mvc 3 .Net FW 4.0 project I have a data that relates in a parent child relationship, I’ve built up my model to contain a list of “children” with each parent record, and displaying it as in the following example:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/ViewMasterPage.Master" Inherits="System.Web.Mvc.ViewPage<MvcTest.Models.ModelList>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
ShowPropReturn
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>ShowPropReturn</h2>
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>
<% using (Html.BeginForm()) { %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>ModelList</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.MyProperty1) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.MyProperty1) %>
<%: Html.ValidationMessageFor(model => model.MyProperty1) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.MyProperty2) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.MyProperty2) %>
<%: Html.ValidationMessageFor(model => model.MyProperty2) %>
</div>
<table>
<% foreach (var item in Model.MyProperty3)
{ %>
<tr>
<td>
<%: Html.TextBoxFor(i => item.string1) %>
</td>
<td>
<%: Html.TextBoxFor(i => item.string2) %>
</td>
</tr>
<% } %>
</table>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
I figured out that if a displayfor is used to only display a field value, it does not get posted back which makes sense. But I’m getting a null for the child list object in the model on httppost and I need to have these items edited on the same view, it is also null in the formcollection object, can anyone help me on this please?
Instead of the
foreachloop try using an editor template:and inside the corresponding editor template (
~/Views/Shared/EditorTemplates/SomeModelType.ascx):Now this will generate proper input field names so that when you submit the form values will be correctly bound.
Remark: In this case I assume that
MyProperty3on your main view model is defined like this (a collection ofSomeModelType):