I have a couple of views in my application that display the same editor template for one of my model elements; of the two views ("Add" and "Change"), "Edit" works fine, but "Add" returns null for the model when my controller action processes the message.
I found that if I give the "Add" view to a custom ViewModel and call Html.EditorFor(p => p.PageContent) , and not just call EditorFor () for the whole Model object - Html.EditorFor(p => p) , then the form will return correct, non-empty, but this causes other problems related to my script and control identifiers on the client side (since now all fields are prefixed with "PageContent_"). I use the same template editor technique in several different places in my application, and none of the others show this odd dependency on ViewModel.
Has anyone else encountered similar problems?
Change view
<%@ Page Title="" Language="C#" MasterPageFile="~/Areas/Admin/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<PageContent>" %> <% using (Html.BeginForm()) { %> <%=Html.Hidden("PageID", Model.Page.ID) %> <%=Html.EditorFor(p => p)%> <input type="submit" name="btnSave" value="Save" /> <input type="submit" name="btnCancel" value="Cancel" class="cancel" /> <% }
Action (working)
[HttpPost, ValidateInput(false)] public ActionResult EditContent(int id, FormCollection formCollection) {}
Add view
<%@ Page Title="" Language="C#" MasterPageFile="~/Areas/Admin/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<PageContent>" %> <% using (Html.BeginForm()) { %> <%=Html.Hidden("PageID", ViewData["PageID"]) %> <%=Html.EditorFor(p => p)%> <input type="submit" name="btnSave" value="Save" /> <input type="submit" name="btnCancel" value="Cancel" class="cancel" /> <% } %>
Action (Failure)
// content is ALWAYS null [HttpPost, ValidateInput(false)] public ActionResult AddContent(PageContent content, FormCollection formCollection) {}
Before you start crying, "duplicate"
This question refers to this , but this question is intended to focus on the specific problem that I am experiencing, and not on the more general question asked there.