C# ASP.NET MVC中下拉列表的帮助器
我正在创建ASP.NET MVC应用程序,我在“注册”页面中的下拉列表有问题 首先,我的模型(由EF在“数据库优先”模式下创建): 注意:用户和国家按CountryId关联(不是集合) 在我的控制器中:C# ASP.NET MVC中下拉列表的帮助器,c#,asp.net-mvc,razor,C#,Asp.net Mvc,Razor,我正在创建ASP.NET MVC应用程序,我在“注册”页面中的下拉列表有问题 首先,我的模型(由EF在“数据库优先”模式下创建): 注意:用户和国家按CountryId关联(不是集合) 在我的控制器中: ViewBag.countries = context.Countries.ToList(); return View(); <select name="CountryId" id="CountryId"> @foreach (var item in ViewBag.co
ViewBag.countries = context.Countries.ToList();
return View();
<select name="CountryId" id="CountryId">
@foreach (var item in ViewBag.countries)
{
<option value="@item.Id" id="@item.Id">@item.Name</option>
}
</select>
在我的视图中:
ViewBag.countries = context.Countries.ToList();
return View();
<select name="CountryId" id="CountryId">
@foreach (var item in ViewBag.countries)
{
<option value="@item.Id" id="@item.Id">@item.Name</option>
}
</select>
但是做工作是不可能的
ASP.NET视图的默认代码为:
<div class="form-group">
@Html.LabelFor(model => model.CountryId, "CountryId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("CountryId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CountryId, "", new { @class = "text-danger" })
</div>
</div>
@LabelFor(model=>model.CountryId,“CountryId”,htmlAttributes:new{@class=“controllabel col-md-2”})
@DropDownList(“CountryId”,null,htmlAttributes:new{@class=“form control”})
@Html.ValidationMessageFor(model=>model.CountryId,“,new{@class=“text danger”})
这段代码会抛出以下错误:
其他信息:没有键为“CountryId”的“IEnumerable”类型的ViewData项
有什么建议吗提前感谢 “它不起作用”不是一个问题陈述。告诉我们实际发生了什么。谢谢,我用关于主题的更多信息完成了问题。错误似乎是不言自明的。而不是
ViewBag.countries=context.countries.ToList()代码>,尝试将其放入ViewData中。e、 g.ViewData[“CountryId”]=context.Countries.ToList()代码>