如何在MVC项目中的参考表中创建下拉列表



我创建了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; }


    }

}

这是控制器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;
        }
    }
}

这是查看logtypecreate.cshtml 代码来创建新的LogType数据:

@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

谢谢。

i已经从 @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:ProjectsVS2012Websitei_insurancei_insuranceViewsLogTypeLogTypeUpdate.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:ProjectsVS2012Websitei_insurancei_insuranceViewsLogTypeLogTypeUpdate.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

首先,您必须创建 dataAccess for tblrecstatus 表才能从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; }
        }
        ...
    }
}

在控制器中, logTypecontroller ,您必须将数据绑定到Method logTypecReate的下拉列表(这不是httppost方法),请参见下面的代码:

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

在视图中

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

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

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

然后在您的视图中做这个

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

最新更新