Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在mvc项目中从参考表创建dropdownlist_C#_Asp.net Mvc_Entity Framework - Fatal编程技术网

C# 如何在mvc项目中从参考表创建dropdownlist

C# 如何在mvc项目中从参考表创建dropdownlist,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我创建了MVC项目并使用EF获取数据 这是TBLRG的表格结构 RecStatusId int RecStatusName nvarchar(20) RecStatusDecr nvarchar(100) CreateOn datetime CreateBy int ModifyOn datetime ModifyBy int 这是tblLogType的表结构 LogTypeId int LogTypeCode

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

这是TBLRG的表格结构

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具有TBLRG.RecStatusId的外键

tblLogType.RecStatusId = LogType.RecStatusId;
LogTypeDA的数据访问

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

        }

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




    }


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

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

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

我已经测试了来自@Motomoto Pink的解决方案,它对dropdownlist有效 当我尝试创建新数据或更新数据日志类型并将所有字段留空时,仍然存在问题

以下是错误代码:

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

[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
[InvalidOperationException:具有键'RecStatusId'的ViewData项的类型为'System.Int32',但必须为'IEnumerable'类型。]
System.Web.Mvc.Html.SelectExtensions.GetSelectData(HtmlHelper HtmlHelper,字符串名)+355
System.Web.Mvc.Html.SelectExtensions.SelectInternal(HtmlHelper HtmlHelper、ModelMetadata元数据、字符串选项标签、字符串名称、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.\页面\视图\日志类型\日志类型更新\ cshtml.Execute()位于d:\Projects\VS2012\Website\i\u insurance\i\u 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、TextWriter、Object实例)+235
System.Web.Mvc.buildmanager compiledview.Render(ViewContext、TextWriter)+107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext上下文)+291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext ControllerContext,ActionResult ActionResult)+13
System.Web.Mvc.c__显示Class1A.b_17()+23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter筛选器,ResultExecutingContext预文本,Func`1 continuation)+245
System.Web.Mvc.c__DisplayClass1c.b__19()+22
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter筛选器,ResultExecutingContext预文本,Func`1 continuation)+245
System.Web.Mvc.c__DisplayClass1c.b__19()+22
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext ControllerContext,ILST`1过滤器,ActionResult ActionResult)+176
System.Web.Mvc.Async.c__显示Class2A.b__20()+75
System.Web.Mvc.Async.c__显示类25.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__;u displayClassId.b__u18(IAsyncResult asyncResult)+14
System.Web.Mvc.Async.c__显示类4.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__显示类4.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__;u DisplayClass8.b__;u 3(IAsyncResult asyncResult)+25
System.Web.Mvc.Async.c__显示类4.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.IHTTPassynchandler.EndProcessRequest(IAsyncResult结果)+9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()+9634212
System.Web.HttpApplication.ExecuteStep(IExecutionStep步骤,布尔值&同步完成)+155

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

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

首先,您必须为tblrNegatus表创建DataAccess,以从tblrNegatus获取所有数据(可能您已经拥有了它)


您好,Gjohn,我已经更新了我的LogTypeModel,并根据您的建议更新了我的视图,但我收到以下错误:错误1“StatusList”名称在VS indicator当前上下文中不存在此代码中的错误:new SelectList(StatusList,StatusList似乎不可用,对此有其他要求吗?嗨,Motomoto,我在LogTypeCreate.cshtml页面中创建新日志类型时尝试了一些新的方法,并在所有字段中填充空白,然后按下按钮创建此错误出现在@Html.DropDownListFor中(model=>model.RecStatusId,model.RecordStatusList)错误信息:具有键“RecStatusId”的ViewData项的类型为“System.Int32”,但必须为“IEnumerable”。为什么会发生这种情况,以及我如何解决此问题?谢谢。我可以查看您的新日志类型来调查此问题吗?是的,您可以,我已经更新了主要问题中的代码,以及如何设置dropdownlist recor的默认值d创建新数据时的状态[我想在dropdownlist中设置活动值]?是的,您可以设置默认的选择值,请参阅LogTypeController代码中的,我更新了答案。我已尝试在我的控制器Selected=s.RecStatusId.ToString()中添加代码但是selected是bool属性,当我添加代码时会产生错误。那么当我在@Html.DropDownListFor中提交新的空白数据时会出现错误吗
[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
prop List<TblRecStatus> StatusList {get; set;}
@Html.DropDownListFor(m => m.StatusList, new SelectList(StatusList, "StatusID", "StatusName"))
public class RecStatusDA : BaseDA
{
    public List<tblRecStatus> GetAll()
    {
       return (from tblRecStatus s in this.DataContext.tblRecStatus
                    select s).ToList();
    }
}
namespace i_insurance.Models
{
    public class LogTypeModel
    {
        public class LogType
        {
         ...
         public IEnumerable<SelectListItem> selectList { get; set; }
        }
        ...
    }
}
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>
tblLogType.RecStatusId = LogType.RecStatusId;