title: How to create dropdownlist from reference table in mvc project
body: <p>I created MVC project and use EF to get data,</p>
  
  <p>Here is the <strong>table stucture for tblRecStatus</strong></p>
  
  <pre><code>RecStatusId     int
  RecStatusName   nvarchar(20)
  RecStatusDecr   nvarchar(100)
  CreateOn        datetime
  CreateBy        int
  ModifyOn        datetime
  ModifyBy        int
  </code></pre>
  
  <p>And here is the <strong>table stucture for tblLogType</strong></p>
  
  <pre><code>LogTypeId       int
  LogTypeCode     nvarchar(2)
  LogTypeName     nvarchar(20)
  LogTypeDecr     nvarchar(100)
  RecStatusId     int
  CreateOn        datetime
  CreateBy        int
  ModifyOn        datetime
  ModifyBy        int
  </code></pre>
  
  <p>tblLogType.RecStatusId have foreign key to tblRecStatus.RecStatusId</p>
  
  <p>The <strong>DataAccess for LogTypeDA</strong> :</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  
  namespace i_insurance.DataAccess
  {
      public class LogTypeDA : BaseDA
      {
          public List&lt;tblLogType&gt; GetAll()
          {
              return (from tblLogType o in this.DataContext.tblLogTypes
                      select o).ToList();
          }
  
          public tblLogType GetById(int Id)
          {
              return (from tblLogType o in this.DataContext.tblLogTypes
                      where o.LogTypeId == Id
                      select o).SingleOrDefault();
          }
  
  
          public void Insert(tblLogType tblLogType)
          {
              try
              {
                  this.DataContext.tblLogTypes.Add(tblLogType);
                  this.DataContext.SaveChanges();
              }
              catch (Exception)
              {
  
                  throw;
              }
  
          }
  
          public void Delete(int Id)
          {
              try
              {
                  tblLogType tblLogTypeOnDb = (from tblLogType o in this.DataContext.tblLogTypes
                                       where o.LogTypeId == Id
                                       select o).SingleOrDefault();
  
                  this.DataContext.tblLogTypes.Remove(tblLogTypeOnDb);
                  this.DataContext.SaveChanges();
              }
              catch (Exception)
              {
  
                  throw;
              }
  
          }
  
  
          public void Update(tblLogType tblLogType)
          {
              try
              {
                  tblLogType tblLogTypeOnDb = (from tblLogType o in this.DataContext.tblLogTypes
                                               where o.LogTypeId == tblLogType.LogTypeId
                                       select o).SingleOrDefault();
  
                  tblLogTypeOnDb.LogTypeCode = tblLogType.LogTypeCode;
                  tblLogTypeOnDb.LogTypeName = tblLogType.LogTypeName;
                  tblLogTypeOnDb.LogTypeDecr = tblLogType.LogTypeDecr;
                  tblLogTypeOnDb.RecStatusId = tblLogType.RecStatusId;
                  tblLogTypeOnDb.ModifyOn = tblLogType.ModifyOn;
                  tblLogTypeOnDb.ModifyBy = tblLogType.ModifyBy;
  
                  this.DataContext.SaveChanges();
              }
              catch (Exception)
              {
  
                  throw;
              }
  
          }
  
      }
  }
  </code></pre>
  
  <p>The <strong>Model for this LogTypeModel</strong> :</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  
  using System.ComponentModel.DataAnnotations;
  using System.Text;
  using i_insurance.DataAccess;
  using System.Web.Mvc;
  
  namespace i_insurance.Models
  {
      public class LogTypeModel
      {
  
          public class LogType
          {
              [Key]
              public int LogTypeId { get; set; }
  
              [Required(ErrorMessage = "Log Type Code is required.")]
              [Display(Name = "Log Type Code")]
              [MaxLength(2)]
              public string LogTypeCode { get; set; }
  
              [Required(ErrorMessage = "Log Type Name is required.")]
              [Display(Name = "Log Type Name")]
              [MaxLength(20)]
              public string LogTypeName { get; set; }
  
              [Display(Name = "Log Type Description")]
              [MaxLength(100)]
              public string LogTypeDecr { get; set; }
  
              [Display(Name = "Record Status")]
              public int? RecStatusId { get; set; }
  
              [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy hh:mm:ss}", ApplyFormatInEditMode = true)]
              public DateTime? CreateOn { get; set; }
  
              public int? CreateBy { get; set; }
  
              [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy hh:mm:ss}", ApplyFormatInEditMode = true)]
              public DateTime? ModifyOn { get; set; }
  
              public int? ModifyBy { get; set; }
  
              // additional column, example column from other table
              public string RecStatusName { get; set; }
              public string CreateByUserName { get; set; }
              public string ModifyByUserName { get; set; }
  
              public IEnumerable&lt;SelectListItem&gt; RecordStatusList { get; set; }
  
          }
  
          public LogTypeModel()
          {
              this.LogTypeList = new List&lt;LogType&gt;();
          }
  
          public List&lt;LogType&gt; LogTypeList { get; set; }
  
  
  
  
      }
  
  
  }
  </code></pre>
  
  <p>Here is the <strong>Controller LogTypeController</strong> : </p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using System.Web.Mvc;
  
  using i_insurance.Models;
  using i_insurance.DataAccess;
  using System.Data;
  using System.Web.Security;
  using i_insurance.Filters;
  using i_insurance;
  
  
  
  namespace i_insurance.Controllers
  {
      [Authorize]
      [InitializeSimpleMembership]
      public class LogTypeController : Controller
      {
          //
          // GET: /Log/
  
  
  
  
          public ActionResult Index()
          {
              return View();
          }
  
  
          public ActionResult LogTypeIndex()
          {
              LogTypeDA LogTypeDA = new LogTypeDA();
              List&lt;tblLogType&gt; lsTblLogType;
  
              lsTblLogType = LogTypeDA.GetAll();
              LogTypeModel model = new LogTypeModel();
  
              RecStatusDA RecStatusDA = new RecStatusDA();
  
              foreach (tblLogType o in lsTblLogType)
              {
                  LogTypeModel.LogType LogType = new LogTypeModel.LogType();
  
                  LogType.LogTypeId = o.LogTypeId;
                  LogType.LogTypeCode = o.LogTypeCode;
                  LogType.LogTypeName = o.LogTypeName;
                  LogType.LogTypeDecr = o.LogTypeDecr;
                  LogType.RecStatusId = o.RecStatusId;
                  LogType.CreateOn = o.CreateOn;
                  LogType.CreateBy = o.CreateBy;
                  LogType.ModifyOn = o.ModifyOn;
                  LogType.ModifyBy = o.ModifyBy;
  
                  //additional column
                  LogType.RecStatusName = o.tblRecStatu.RecStatusName;
                  LogType.CreateByUserName = o.UserProfile.UserName;
                  LogType.ModifyByUserName = o.UserProfile1.UserName;
  
                  model.LogTypeList.Add(LogType);
              }
  
              return View(model);
          }
  
  
  
  
          //[HttpGet]
          public ActionResult LogTypeCreate()
          {
              //ViewBag.RecStatusList = new RecStatusDA().GetAll();
              //return View();
              var model = new LogTypeModel.LogType { RecordStatusList = HelperController.GetAllRecStatus() };
              return View(model);
  
          }
  
          [HttpPost]
          public ActionResult LogTypeCreate(LogTypeModel.LogType LogType)
          {
              try
              {
                  if (ModelState.IsValid)
                  {
                      DateTime CurrentTime = new DateTime();
                      CurrentTime = DateTime.Now;
  
                      LogTypeDA LogTypeDA = new LogTypeDA();
                      tblLogType tblLogType = new tblLogType();
  
                      tblLogType.LogTypeCode = LogType.LogTypeCode;
                      tblLogType.LogTypeName = LogType.LogTypeName;
                      tblLogType.LogTypeDecr = LogType.LogTypeDecr;
                      tblLogType.RecStatusId = LogType.RecStatusId;
                      tblLogType.CreateOn = CurrentTime;
                      tblLogType.CreateBy = WebMatrix.WebData.WebSecurity.CurrentUserId;
                      tblLogType.ModifyOn = CurrentTime;
                      tblLogType.ModifyBy = WebMatrix.WebData.WebSecurity.CurrentUserId;
  
                      LogTypeDA.Insert(tblLogType);
                      return RedirectToAction("LogTypeIndex");
                  }
  
              }
              catch (Exception)
              {
  
                  throw;
              }
              return View(LogType);
          }
  
  
          // GET: /Log/LogTypeDelete/5
          public ActionResult LogTypeDelete(int Id, bool? saveChangesError)
          {
              if (saveChangesError.GetValueOrDefault())
              {
                  ViewBag.ErrorMessage = "Unable to save changes. Try again, and if the problem persists see your system administrator.";
              }
  
              LogTypeDA LogTypeDA = new LogTypeDA();
              tblLogType tblLogType = new tblLogType();
              tblLogType = LogTypeDA.GetById(Id);
  
              LogTypeModel.LogType model = new LogTypeModel.LogType();
              model.LogTypeCode = tblLogType.LogTypeCode;
              model.LogTypeName = tblLogType.LogTypeName;
              model.LogTypeDecr = tblLogType.LogTypeDecr;
  
  
              return View(model);
          }
  
  
          // POST: /Log/LogTypeDelete/5
          [HttpPost, ActionName("LogTypeDelete")]
          public ActionResult LogTypeDelete(int Id)
          {
              LogTypeDA LogTypeDA = new LogTypeDA();
              LogTypeDA.Delete(Id);
  
              return RedirectToAction("LogTypeIndex");
          }
  
  
          public ActionResult LogTypeRead(int Id)
          {
              LogTypeDA LogTypeDA = new LogTypeDA();
              tblLogType tblLogType = LogTypeDA.GetById(Id);
  
              LogTypeModel.LogType model = new LogTypeModel.LogType();
  
              model.LogTypeId = tblLogType.LogTypeId;
              model.LogTypeCode = tblLogType.LogTypeCode;
              model.LogTypeName = tblLogType.LogTypeName;
              model.LogTypeDecr = tblLogType.LogTypeDecr;
              model.RecStatusId = tblLogType.RecStatusId;
              model.CreateOn = tblLogType.CreateOn;
              model.CreateBy = tblLogType.CreateBy;
              model.ModifyOn = tblLogType.ModifyOn;
              model.ModifyBy = tblLogType.ModifyBy;
  
              //for additional column
              model.RecStatusName = tblLogType.tblRecStatu.RecStatusName;
              model.CreateByUserName = tblLogType.UserProfile.UserName;
              model.ModifyByUserName = tblLogType.UserProfile1.UserName;
  
  
              return View(model);
  
          }
  
          // GET: /Log/LogTypeUpdate/5
          public ActionResult LogTypeUpdate(int Id)
          {
              LogTypeDA LogTypeDA = new LogTypeDA();
              tblLogType tblLogType = new tblLogType();
              tblLogType = LogTypeDA.GetById(Id);
  
              LogTypeModel.LogType model = new LogTypeModel.LogType();
  
              model.LogTypeId = Id;
              model.LogTypeCode = tblLogType.LogTypeCode;
              model.LogTypeName = tblLogType.LogTypeName;
              model.LogTypeDecr = tblLogType.LogTypeDecr;
              model.RecStatusId = tblLogType.RecStatusId;
  
              // for dropdownlist value
              //ViewBag.RecStatusList = new RecStatusDA().GetAll();
              model.RecordStatusList = HelperController.GetAllRecStatus();
  
              return View(model);
  
          }
  
  
          // POST: /Log/LogType/Edit/5
          [HttpPost]
          public ActionResult LogTypeUpdate(LogTypeModel.LogType LogType)
          {
  
              try
              {
                  if (ModelState.IsValid)
                  {
                      LogTypeDA LogTypeDA = new LogTypeDA();
                      tblLogType tblLogType = new tblLogType();
  
                      DateTime CurrentDateTime = new DateTime();
                      CurrentDateTime = DateTime.Now;
  
  
                      tblLogType.LogTypeId = LogType.LogTypeId;
                      tblLogType.LogTypeCode = LogType.LogTypeCode;
                      tblLogType.LogTypeName = LogType.LogTypeName;
                      tblLogType.LogTypeDecr = LogType.LogTypeDecr;
                      tblLogType.RecStatusId = LogType.RecStatusId;
                      tblLogType.ModifyOn = CurrentDateTime;
                      tblLogType.ModifyBy = WebMatrix.WebData.WebSecurity.CurrentUserId;
  
                      LogTypeDA.Update(tblLogType);
                      return RedirectToAction("LogTypeIndex");
                  }
              }
              catch (DataException)
              {
                  //Log the error (add a variable name after DataException)
                  ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
              }
              return View(LogType);
          }
      }
  }
  </code></pre>
  
  <p>Here is the <strong>general class function in controller</strong> :</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using System.Web.Mvc;
  
  using i_insurance.Models;
  using i_insurance.DataAccess;
  using System.Data;
  
  namespace i_insurance
  {
      public class HelperController : Controller
      {
  
          public static IEnumerable&lt;SelectListItem&gt; GetAllRecStatus()
          {
              var recStatusDA = new RecStatusDA();
              IEnumerable&lt;SelectListItem&gt; slItem = from s in recStatusDA.GetAll()
                                                   select new SelectListItem
                                                   {
                                                       Text = s.RecStatusName,
                                                       Value = s.RecStatusId.ToString()
                                                   };
  
              return slItem;
          }
  
      }
  }
  </code></pre>
  
  <p>Here is the <strong>View LogTypeCreate.cshtml</strong> code to create new LogType data:</p>
  
  <pre><code>@model i_insurance.Models.LogTypeModel.LogType
  
  @{
      ViewBag.Title = "Create New Log Type";
  }
  
  &lt;h2&gt;@ViewBag.Title&lt;/h2&gt;
  
  @*&lt;script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"&gt;&lt;/script&gt;
  &lt;script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"&gt;&lt;/script&gt;*@
  
  @using (Html.BeginForm())
  {
      @Html.AntiForgeryToken()
      @Html.ValidationSummary()
  
      &lt;fieldset&gt;
          &lt;legend&gt;Log Type&lt;/legend&gt;
  
          &lt;br /&gt;
          &lt;br /&gt;
  
          &lt;table&gt;
              &lt;tr&gt;
                  &lt;td&gt;@Html.LabelFor(model =&gt; model.LogTypeCode)&lt;/td&gt;
                  &lt;td&gt;:&lt;/td&gt;
                  &lt;td&gt;
                      @Html.EditorFor(model =&gt; model.LogTypeCode)
                      @Html.ValidationMessageFor(model =&gt; model.LogTypeCode)
                  &lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;@Html.LabelFor(model =&gt; model.LogTypeName)&lt;/td&gt;
                  &lt;td&gt;:&lt;/td&gt;
                  &lt;td&gt;
                      @Html.EditorFor(model =&gt; model.LogTypeName)
                      @Html.ValidationMessageFor(model =&gt; model.LogTypeName)
                  &lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;@Html.LabelFor(model =&gt; model.LogTypeDecr)&lt;/td&gt;
                  &lt;td&gt;:&lt;/td&gt;
                  &lt;td&gt;
                      @Html.EditorFor(model =&gt; model.LogTypeDecr)
                      @Html.ValidationMessageFor(model =&gt; model.LogTypeDecr)
                  &lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;@Html.LabelFor(model =&gt; model.RecStatusId)&lt;/td&gt;
                  &lt;td&gt;:&lt;/td&gt;
                  &lt;td&gt;
                      @*@Html.DropDownListFor(model=&gt;model.RecStatusId, new SelectList(ViewBag.RecStatusList,"RecStatusId","RecStatusName"))*@
                      @Html.DropDownListFor(model =&gt; model.RecStatusId, Model.RecordStatusList)
                      @Html.ValidationMessageFor(model =&gt; model.RecStatusId)
                  &lt;/td&gt;
              &lt;/tr&gt;
          &lt;/table&gt;
  
  
          &lt;p&gt;
              &lt;input type="submit" value="Create" /&gt;
          &lt;/p&gt;
      &lt;/fieldset&gt;
  }
  
  &lt;div&gt;
      @Html.ActionLink("Back to List", "LogTypeIndex")
  &lt;/div&gt;
  </code></pre>
  
  <p>My question how to make this mvc view support dropdownlist from reference table tblRecStatus ?</p>
  
  <pre><code>With 
  BindText  = tblRecStatus.RecStatusName
  BindValue = tblRecStatus.RecStatusId (0  = dis active, 1 = active)
  
  Example :
  Dropdownlist will contain
   - Dis Active
   - Active
  
  if user choose Active, it will save value 1 for column tblLogType.RecStatusId
  </code></pre>
  
  <p>Thank You.</p>
  
  <p>I already test solution from <strong>@Motomoto Pink</strong>, and it worked for dropdownlist 
  and still have issue when i try to create new data or update data logType with leave all field blank</p>
  
  <p>Here is the error code :</p>
  
  <pre><code>The ViewData item that has the key 'RecStatusId' is of type 'System.Int32' but must be of type 'IEnumerable&lt;SelectListItem&gt;'. 
  </code></pre>
  
  <p><strong>Source Error</strong> :</p>
  
  <pre><code>@Html.DropDownListFor(model =&gt; model.RecStatusId, Model.RecordStatusList)
  
  Source File: d:\Projects\VS2012\Website\i_insurance\i_insurance\Views\LogType\LogTypeUpdate.cshtml    Line: 48 
  </code></pre>
  
  <p><strong>Stack Trace:</strong></p>
  
  <pre><code>[InvalidOperationException: The ViewData item that has the key 'RecStatusId' is of type 'System.Int32' but must be of type 'IEnumerable&lt;SelectListItem&gt;'.]
     System.Web.Mvc.Html.SelectExtensions.GetSelectData(HtmlHelper htmlHelper, String name) +355
     System.Web.Mvc.Html.SelectExtensions.SelectInternal(HtmlHelper htmlHelper, ModelMetadata metadata, String optionLabel, String name, IEnumerable`1 selectList, Boolean allowMultiple, IDictionary`2 htmlAttributes) +142
     System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper`1 htmlHelper, Expression`1 expression, IEnumerable`1 selectList, String optionLabel, IDictionary`2 htmlAttributes) +94
     System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper`1 htmlHelper, Expression`1 expression, IEnumerable`1 selectList) +60
     ASP._Page_Views_LogType_LogTypeUpdate_cshtml.Execute() in d:\Projects\VS2012\Website\i_insurance\i_insurance\Views\LogType\LogTypeUpdate.cshtml:48
     System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
     System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103
     System.Web.WebPages.StartPage.RunPage() +17
     System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
     System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
     System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
     System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
     System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
     System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
     System.Web.Mvc.&lt;&gt;c__DisplayClass1a.&lt;InvokeActionResultWithFilters&gt;b__17() +23
     System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245
     System.Web.Mvc.&lt;&gt;c__DisplayClass1c.&lt;InvokeActionResultWithFilters&gt;b__19() +22
     System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245
     System.Web.Mvc.&lt;&gt;c__DisplayClass1c.&lt;InvokeActionResultWithFilters&gt;b__19() +22
     System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +176
     System.Web.Mvc.Async.&lt;&gt;c__DisplayClass2a.&lt;BeginInvokeAction&gt;b__20() +75
     System.Web.Mvc.Async.&lt;&gt;c__DisplayClass25.&lt;BeginInvokeAction&gt;b__22(IAsyncResult asyncResult) +99
     System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
     System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
     System.Web.Mvc.&lt;&gt;c__DisplayClass1d.&lt;BeginExecuteCore&gt;b__18(IAsyncResult asyncResult) +14
     System.Web.Mvc.Async.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult ar) +23
     System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
     System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
     System.Web.Mvc.Async.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult ar) +23
     System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
     System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
     System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
     System.Web.Mvc.&lt;&gt;c__DisplayClass8.&lt;BeginProcessRequest&gt;b__3(IAsyncResult asyncResult) +25
     System.Web.Mvc.Async.&lt;&gt;c__DisplayClass4.&lt;MakeVoidDelegate&gt;b__3(IAsyncResult ar) +23
     System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
     System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
     System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
     System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9634212
     System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +155
  </code></pre>