I am trying to implement my editing action methods with a strongly typed view that gets a custom view of the ViewModel class. In other words, I want a strongly typed ViewModel that contains a Linq object that needs to be edited, as well as several other objects that need to be displayed in the view.
I see the view when I call the GET Edit action method, but the strict action of the POST method only gets the ViewModel class with zero parameters, and I can't figure out how to get the POST parameters.
The view model is as follows:
//my custom-shaped ViewModel public class CustomersFormViewModel { public SelectList AccountTypesDropDownBox; public SelectList CountriesDropDownBox; public Customer Customer; }
The action method is as follows:
// // GET: /CustomersController/Edit public ActionResult Edit(int ID) { var model = new CustomersFormViewModel { Customer = repository.Load(ID.Value), CountriesDropDownBox = GetCountries(), AccountTypesDropDownBox = GetAccountTypes() }; return View(model); } // // POST: /CustomersController/Edit [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(CustomersFormViewModel model) { //THE NEXT LINE THROWS!!! Debug.Assert(Model.Customer!=null); return View(model); }
And this is my edit:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/CustAdminMaster.master" Inherits="System.Web.Mvc.ViewPage<Zeiterfassung.Controllers.CustomersController+CustomersFormViewModel>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> NewEdit </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2> NewEdit</h2> <%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %> <% using (Html.BeginForm()) {%> <fieldset> <legend>Fields</legend> <p> <label for="FirstName">FirstName:</label> <%= Html.TextBox("FirstName",Model.Customer.FirstName) %> <%= Html.ValidationMessage("FirstName", "*") %> </p> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> <div> <%=Html.ActionLink("Back to List", "Index") %> </div> </asp:Content>
I also tried the POST action method with formValues parameters, but the view model still did not contain the published parameters:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int ID, FormCollection formValues) { CustomersFormViewModel model = new CustomersFormViewModel(); UpdateModel(model);
The only way I've found so far is to write custom code that captures published parameters from FormCollection and accordingly updates my own ViewModel. But this approach seems a bit primitive. Is there a better way to do this?
EDIT: I just tried a different syntax in the view, as tvanfosson suggested, but the problem remains the same:
<label for="Customer.FirstName">FirstName:</label> <%= Html.TextBox("Customer.FirstName") %> <%= Html.ValidationMessage("Customer.FirstName", "*") %>