如何在mvc项目中从引用表创建下拉列表

时间:2014-02-04 03:53:34

标签: c# asp.net-mvc entity-framework

我创建了MVC项目并使用EF来获取数据,

以下是tblRecStatus的表结构

RecStatusId     int
RecStatusName   nvarchar(20)
RecStatusDecr   nvarchar(100)
CreateOn        datetime
CreateBy        int
ModifyOn        datetime
ModifyBy        int

这是tblLogType

表结构
LogTypeId       int
LogTypeCode     nvarchar(2)
LogTypeName     nvarchar(20)
LogTypeDecr     nvarchar(100)
RecStatusId     int
CreateOn        datetime
CreateBy        int
ModifyOn        datetime
ModifyBy        int

tblLogType.RecStatusId具有tblRecStatus.RecStatusId的外键

LogTypeDA的DataAccess

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<tblLogType> 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;
            }

        }

    }
}

此LogTypeModel的模型

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<SelectListItem> RecordStatusList { get; set; }

        }

        public LogTypeModel()
        {
            this.LogTypeList = new List<LogType>();
        }

        public List<LogType> LogTypeList { get; set; }




    }


}

这是 Controller LogTypeController

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<tblLogType> 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);
        }
    }
}

以下是控制器中的常规类函数:

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<SelectListItem> GetAllRecStatus()
        {
            var recStatusDA = new RecStatusDA();
            IEnumerable<SelectListItem> slItem = from s in recStatusDA.GetAll()
                                                 select new SelectListItem
                                                 {
                                                     Text = s.RecStatusName,
                                                     Value = s.RecStatusId.ToString()
                                                 };

            return slItem;
        }

    }
}

以下是用于创建新LogType数据的查看LogTypeCreate.cshtml 代码:

@model i_insurance.Models.LogTypeModel.LogType

@{
    ViewBag.Title = "Create New Log Type";
}

<h2>@ViewBag.Title</h2>

@*<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>*@

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    <fieldset>
        <legend>Log Type</legend>

        <br />
        <br />

        <table>
            <tr>
                <td>@Html.LabelFor(model => model.LogTypeCode)</td>
                <td>:</td>
                <td>
                    @Html.EditorFor(model => model.LogTypeCode)
                    @Html.ValidationMessageFor(model => model.LogTypeCode)
                </td>
            </tr>
            <tr>
                <td>@Html.LabelFor(model => model.LogTypeName)</td>
                <td>:</td>
                <td>
                    @Html.EditorFor(model => model.LogTypeName)
                    @Html.ValidationMessageFor(model => model.LogTypeName)
                </td>
            </tr>
            <tr>
                <td>@Html.LabelFor(model => model.LogTypeDecr)</td>
                <td>:</td>
                <td>
                    @Html.EditorFor(model => model.LogTypeDecr)
                    @Html.ValidationMessageFor(model => model.LogTypeDecr)
                </td>
            </tr>
            <tr>
                <td>@Html.LabelFor(model => model.RecStatusId)</td>
                <td>:</td>
                <td>
                    @*@Html.DropDownListFor(model=>model.RecStatusId, new SelectList(ViewBag.RecStatusList,"RecStatusId","RecStatusName"))*@
                    @Html.DropDownListFor(model => model.RecStatusId, Model.RecordStatusList)
                    @Html.ValidationMessageFor(model => model.RecStatusId)
                </td>
            </tr>
        </table>


        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "LogTypeIndex")
</div>

我的问题如何从参考表tblRecStatus中获取此mvc视图支持下拉列表?

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

谢谢。

我已经从 @Motomoto Pink 测试了解决方案,它适用于下拉列表 当我尝试创建新数据或更新数据logType并将所有字段留空时仍然有问题

以下是错误代码:

The ViewData item that has the key 'RecStatusId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. 

来源错误

@Html.DropDownListFor(model => model.RecStatusId, Model.RecordStatusList)

Source File: d:\Projects\VS2012\Website\i_insurance\i_insurance\Views\LogType\LogTypeUpdate.cshtml    Line: 48 

堆栈追踪:

[InvalidOperationException: The ViewData item that has the key 'RecStatusId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.]
   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.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +22
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +22
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +176
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +75
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>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.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>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.<>c__DisplayClass4.<MakeVoidDelegate>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.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>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& completedSynchronously) +155

2 个答案:

答案 0 :(得分:1)

首先,您必须为 tblRecStatus 表创建 DataAccess 以从tblRecStatus获取所有数据(也许您已经拥有它)

public class RecStatusDA : BaseDA
{
    public List<tblRecStatus> GetAll()
    {
       return (from tblRecStatus s in this.DataContext.tblRecStatus
                    select s).ToList();
    }
}

接下来,在 LogTypeModel.LogType 类中添加一个属性,用于管理来自tblRecStatus的数据

namespace i_insurance.Models
{
    public class LogTypeModel
    {
        public class LogType
        {
         ...
         public IEnumerable<SelectListItem> selectList { get; set; }
        }
        ...
    }
}

在Controller中, LogTypeController ,您必须在方法LogTypeCreate(不是HttpPost方法)中将数据绑定到DropDownList,请参阅下面的代码:

private IEnumerable<SelectListItem> GetAllRecStatus()
{
    var recStatusDA = new RecStatusDA();
    IEnumerable<SelectListItem> slItem = from s in recStatusDA.GetAll()
                                            select new SelectListItem
                                            {
                                                Selected = s.RecStatusId.ToString() == "default value you want to set"
                                                Text = s.RecStatusName,
                                                Value = s.RecStatusId.ToString()
                                            };
    return slItem;
}

public ActionResult LogTypeCreate()
{
    var model = new LogTypeModel.LogType { selectList = GetAllRecStatus() };
    return View(model);
}

在视图 LogTypeCreate.cshtml 中,定义DropDownList

<tr>
   <td>Status</td>
   <td>:</td>
   <td>
        @Html.DropDownListFor(model => model.RecStatusId, Model.selectList)
   </td>
</tr>

最后,请参阅 LogTypeCreate(HttpPost方法),您可以将选定的ResStatusId设置为tblLogType.RecStatusId

tblLogType.RecStatusId = LogType.RecStatusId;

答案 1 :(得分:0)

您需要在模型中指定一个包含下拉列表中所有元素的集合。

prop List<TblRecStatus> StatusList {get; set;}

然后在你看来就这样做

@Html.DropDownListFor(m => m.StatusList, new SelectList(StatusList, "StatusID", "StatusName"))