A day with .Net

My day to day experince in .net

How to implement a dropdownlist in MVC.

Posted by vivekcek on February 25, 2014

1. Create a viewmodel class as below.

public class AddProductViewModel
    {

        [Display(Name="Category")]
        public string CategoryId { get; set; }

        public List<SelectListItem> Categories { get; set; }
    }

2. Create the controller as below.

public class ProductController : Controller
    {
        
        [HttpGet]
        public ActionResult AddProduct()
        {
            AddProductViewModel model = new AddProductViewModel();
            List<SelectListItem> categories = new List<SelectListItem> {
            new SelectListItem{  Value="1",   Text="First"},
            new SelectListItem{  Value="2",   Text="Second"},
            };
            model.Categories = categories;
            return View(model);
        }

        [HttpPost]
        public ActionResult AddProduct(AddProductViewModel model)
        {
            return RedirectToAction("AddProduct");
        }

    }

3. Create a View

@model AAElectronics.ViewModel.AddProductViewModel
@{
    ViewBag.Title = "AddProduct";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>AddProduct</h2>


@using (Html.BeginForm("AddProduct", "Product", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <div>
        @Html.DropDownListFor(m => m.CategoryId, Model.Categories, "-Select-")
    </div>
   
    <button type="submit">Create</button>
}

The category Id will contain the selected item id

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s