将视图中的下拉列表绑定到表中的列.净MVC4
本文关键字:MVC4 绑定 视图 下拉列表 | 更新日期: 2023-09-27 18:06:26
我是ASP的新手。NET MVC,我将感谢任何帮助我的问题。关于这个话题,我已经做了大量的研究(显然不够)。我需要将下拉列表绑定到表中的特定列,然后在视图中呈现它。我已经有了在控制器中检索表的查询:
public ActionResult SelectAccountEmail()
{
var queryAccountEmail = (from AccountEmail in db.UserBases select AccountEmail)
var selectItems = new SelectList(queryAccountEmail);
return View(selectItems);
}
当将查询绑定到视图中的下拉列表时,我迷路了。@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'.
任何帮助将不胜感激。
提前感谢。
几处不对。首先,更改您的模型以添加以下属性(查看您的视图,它是RecordUploaderMVC4.Models.UserBase
):
public class UserBase
{
public string AccountEmail { get; set; }
public SelectList Emails { get; set; }
//rest of your model
}
然后,在控制器中正确地构建模型:
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)
第一步:首先像这样创建一个模型来保存listfaccountemail
public class AccountEmailViewModel
{
public int AccountEmailId { get; set; }
public string AccountEmailDescription { get; set; }
}
步骤2:创建模型类
public class UserBaseViewModel
{
public IEnumerable<SelectListItem> AccountEmail { get; set; }
public string AccountEmail { get; set; }
}
步骤3:
在控制器 [HttppGet]
public ActionResult SelectAccountEmail()
{
var EmailAccounts = (from AccountEmail in db.UserBases select AccountEmail)
UserBase userbaseViewModel = new UserBase
{
AccountEmail = EmailAccounts.Select(x => new SelectListItem
{
Text = x.AccountEmailDescription,
Value = Convert.ToString(x.AccountEmailId)
}).ToList()
};
return View(userbaseViewModel);
}
步骤4:In View
@model RecordUploaderMVC4.Models.UserBase
@{
ViewBag.Title = "SelectAccountEmail";
}
<h2>SelectAccountEmail</h2>
@Html.ValidationSummary()
<h2>SelectAccountEmail</h2>
@Html.LabelFor(model => model.AccountEmail )
@Html.DropDownListFor(x => x.AccountEmailId, Model.AccountEmail, "Please Select", "")
</div>
<input /type="submit" value="Submit">