You create a new view model with properties for your list and for adding new item,
public class CustomerListViewModel
{
public List<Customer> CustomerList { set;get;} // For showing the existing list
// The below properties are for adding new customer
public string NewCustomerName { set;get;}
public string NewCustomerEmail { set;get;}
}
public class Customer
{
public string Name { set;get;}
}
Now in your GET action, create an object of this, load the CustomerList property and send it to view
public ActionResult Index()
{
var vm = new CustomerListViewModel();
//Hard coding 2 customers for demo. you may replace with data from db
vm.CustomerList= new List<Customer> {
new Customer { CustomerName ="Scott"},
new Customer { CustomerName ="John"},
};
return View(vm);
}
Now your view will be strongly typed to this new view model
@model CustomerListViewModel
<h2>Existing customers</h2>
@foreach(var c in Model.CustomerList)
{
<p>@c.Name</p>
}
<h3>Add new customer</h3>
@using(Html.BeginForm("Add","Customer"))
{
@Html.LabelFor(s=>s.NewCustomerName)
@Html.TextBoxFor(s=>s.NewCustomerName)
@Html.LabelFor(s=>s.NewCustomerEmail)
@Html.TextBoxFor(s=>s.NewCustomerEmail)
<input type="submit" />
}
And in your Add HttpPost action, you can use the same view model as the parameter
[HttpPost]
public ActionResult Add(CustomerListViewModel model)
{
var name = model.NewCustomerName;
var email = model.NewCustomerEmail;
// Save this
// to do :Return something (Redirect to success page)
}