I have the following code, with an existing customer. I need to create a form that created an Order, and pass it to my Controller.
I tried changing my model type on that page to Order instead of Customer, but then I'm gonna have to pass the Order object as well, or at least the OrderId.
Models
public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
public List<Order> Orders { get; set;}
}
public class Order
{
public int Id { set; get; }
public string ItemName { set; get; }
public DateTime SomeDate { set; get; }
}
Controller
public class OrderController : Controller
{
[HttpPost]
public Create ActionResult(Customer customer)
{
// Customer doesn't have the values that it suppose to have
// All fields including the array of orders are null
customerStorage.UpdateOrders(customer);
return ("ItemListPartial", customer.orders);
}
}
View
@model Company.Application.Model.Customer;
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
{
// How can I bind this to Order object ?
// I can't define model as Order, because then I need to pass Customer Separately
@Html.TextBoxFor(o => o.Orders[0].ItemName)
@Html.TextBoxFor(o => o.Orders[0].SomeDate)
<input type="submit" value="Add" />
}
This IMO is how you should be handling this:
Pass customerID in your viewbag if you're really not wanting to make a viewmodel (p.s. It is ok to make a viewmodel!)
your post method:
your cshtml
I suppose you're looking for what this blog article describes: ASP.NET MVC Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries
Quote from the blog: