c# - 使用 ASP.NET MVC4 将 View 中的 DropDownList 绑定(bind)到表中的列

标签 c# asp.net-mvc razor

我是 ASP.NET MVC 的新手,如果对我的问题有任何帮助,我将不胜感激。我已经就此主题进行了大量研究(显然还不够)。我需要将下拉列表绑定(bind)到表中的特定列,然后在 View 中呈现它。我已经有了在 Controller 中检索表的查询:

  public ActionResult SelectAccountEmail()
        {
            var queryAccountEmail = (from AccountEmail in db.UserBases select AccountEmail) 
            var selectItems = new SelectList(queryAccountEmail);
            return View(selectItems); 
        }

在将查询绑定(bind)到 View 中的下拉列表时,我迷路了。

@model RecordUploaderMVC4.Models.UserBase

@{
    ViewBag.Title = "SelectAccountEmail";
}

<h2>SelectAccountEmail</h2>

@Html.LabelFor(model => model.AccountEmail); 

@Html.DropDownList(Model.AccountEmail);  
@Html.ValidationMessageFor(model => model.AccountEmail); 

<input /type="submit" value="Submit">

运行时出现错误:

Server Error in '/' Application.
--------------------------------------------------------------------------------


The model item passed into the dictionary is of type 'System.Web.Mvc.SelectList', but this dictionary requires a model item of type 'RecordUploaderMVC4.Models.UserBase'. 

任何帮助将不胜感激。

提前致谢。

最佳答案

很少有错误。首先,更改您的模型以添加以下属性(查看您的 View ,它是 RecordUploaderMVC4.Models.UserBase):

public class UserBase
{
    public string AccountEmail { get; set; }
    public SelectList Emails { get; set; }
    //rest of your model
}

然后,在 Controller 中正确构建模型:

 public ActionResult SelectAccountEmail()
 {
     UserBase model = new UserBase();
     var queryAccountEmail = (from AccountEmail in db.UserBases select AccountEmail) 
     model.Emails = new SelectList(queryAccountEmail);

     return View(model); 
 }

然后在你看来你可以这样做:

@Html.LabelFor(model => model.AccountEmail)

@Html.DropDownListFor(model => model.AccountEmail, Model.Emails)
@Html.ValidationMessageFor(model => model.AccountEmail)

关于c# - 使用 ASP.NET MVC4 将 View 中的 DropDownList 绑定(bind)到表中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15688074/

相关文章:

c# - 如何使用 JSON 从 WCF REST 服务返回 Base64 编码的字节数组?

asp.net-mvc - ASP.NET MVC session 过期

c# - 在运行时 .NET 核心应用程序中停止执行的异常 : System. Data.SqlClient.SqlException : 'Incorrect syntax near the keyword ' GROUP'. '

c# - asp.net mvc highchart 折线图 json

javascript - 如何使用 jquery 验证动态填充的表单字段?

asp.net - EditorFor 扩展不适用于 Asp.Net MVC 5.1 中的 htmlAttributes

html - 带有razor viewengine的MVC 3中的动态属性值

c# - 快速文本预处理

c# - 从类文件调用函数而不创建该类的对象

c# - 打开 Internet 属性并等待用户关闭它 C#