Assuming you have a PersonsProduct class to represent your model/viewmodel like this
public class PersonsProduct
{
public string PersonName { set;get;}
public IEnumerable<SelectListItem> Products { get; set; }
public string SelectedProductId { get; set; }
//Other Properties
}
In your GET action method, you may initialize the values like this
public ActionResult AddProduct()
{
var objProduct = new PersonsProduct();
objProduct.Products = new[]
{
new SelectListItem { Value = "1", Text = "Book" },
new SelectListItem { Value = "2", Text = "Pen" },
new SelectListItem { Value = "3", Text = "Computer" },
new SelectListItem { Value = "4", Text = "Table" },
new SelectListItem { Value = "5", Text = "Mouse" }
};
// can replace the above line with loading data from Data access layer.
return View(objProduct);
}
And in your View which is strongly typed to PersonsProduct viewmodel
@model PersonsProduct
@using (Html.BeginForm())
{
@Html.DropDownListFor(x => x.SelectedProductId, new SelectList(Model.Products ,"Value","Text"), "Select..")
<input type="submit" value="save" />
}
And in your HTTPPost action, you can get the selected productId like this
[HttpPost]
public ActionResult Index(PersonsProduct model)
{
// check model.SelectedProductId here
}
NEVER HARDCODE LIKE THIS. It is UGLY UGLY UGLY !
This answers your question (without using Database and XML). But I strongly recommend to avoid this hardcoding approach. You should better use different source for the list of products like database / XML file etc.. Otherwise whenever you want to add a new product to the list, you need a recompilation. I hope you will change this code to read Product data from a different source instead of hard coded values.