My question is very similar to this one. The application I'm developing is written in MVC 3 and Razor. It lets its users select items from a store and send each one to a different address.
Here are my ViewModels:
public class DeliveryDetailsViewModel
{
public FromDetailsViewModel From { get; set; }
public IList<ToDetailsViewModel> To { get; set; }
}
public class DetailsViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
public class FromDetailsViewModel : DetailsViewModel
{
public string StreetAddress { get; set; }
public string Suburb { get; set; }
public string Postcode { get; set; }
}
public class ToDetailsViewModel : DetailsViewModel
{
public string Message { get; set; }
}
My View is similar to below.
@model Store.ViewModels.DeliveryDetailsViewModel
@Html.EditorFor(m => m.From)
@Html.EditorFor(m => m.To)
My intention is that a collection of forms (one per item in their shopping cart) will be displayed to enable the user to type different delivery details in. Each form has its own submit button.
The editor template which renders the "To" form is as follows:
@model Store.ViewModels.ToDetailsViewModel
@using (Html.BeginForm("ConfirmTo", "Delivery"))
{
@Html.TextBoxFor(m => m.FirstName)
@Html.TextBoxFor(m => m.LastName)
@Html.TextBoxFor(m => m.Email)
@Html.TextBoxFor(m => m.Message)
<input type="submit" value="Confirm" />
}
My controller:
public class DeliveryController : Controller
{
public ActionResult Index()
{
var model = new DeliveryDetailsViewModel();
model.From = new FromDetailsViewModel();
model.To = new List<ToDetailsViewModel>();
return View(model);
}
public ActionResult ConfirmTo(ToDetailsViewModel toDetails)
{
// Save to database.
}
}
I have a couple of problems:
The "to" editor template isn't rendering anything (though it used to). It cites that the model types don't match (i.e.,
ToDetailsViewModelisn't the same asList<ToDetailsViewModel>), even though I thought editor templates were supposed to append indices to input field names to enable proper binding.When clicking Confirm and submitting the first form in the To list the controller receives the view model with the correct bindings. Submitting any of the following forms (with index 1 or greater) calls the ConfirmTo action and passes a
ToDetailsViewModelwhich is null.
Any help would be appreciated, and if you'd like more information about the problem I'm having or the code I'm using, please don't hesitate to ask.