Wednesday 13 March 2013

MVC 4 - Simple example how to populate drop down list


Watch online:



1. Create new project (MVC 4)
2. Add entity connection
3. Add controller
4. Add
private CompanyTestDatabaseEntities db = new CompanyTestDatabaseEntities();
5. Add dispose method
         protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
6. Add Index Method - it will populate ViewBag with data from database
         public ActionResult Index()
        {
            ViewBag.GroupId = new SelectList(db.GroupMasters, "GroupId", "GroupName");
            return View();
        }
7. Whole Controller code looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestPassingToDropDown.Models;

namespace TestPassingToDropDown.Controllers
{
    public class FirstController : Controller
    {
        private CompanyTestDatabaseEntities db = new CompanyTestDatabaseEntities();
        //
        // GET: /First/

        public ActionResult Index()
        {
            ViewBag.GroupId = new SelectList(db.GroupMasters, "GroupId", "GroupName");
            return View();
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
8. Create view and add the following code to it
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div>
    @Html.DropDownList("GroupId", String.Empty)

</div>
9. That's it.

5 comments:

  1. Disculpa y como recupero los datos en el httppost ?

    ReplyDelete
  2. como obtengo el valor del elemento seleccionado o donde se guarda?

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. @* form method "post"
      @Html.DropDownList("GroupId", String.Empty)
      button type="submit" value="send" </button
      form *@

      Delete
  4. What is "base" in "base.Dispose(disposing);"

    ReplyDelete