【发布时间】:2017-01-26 13:12:51
【问题描述】:
我有一个 MVC 5 站点,我想使用带有 ViewModel 的强类型 DropDownListFor - 而不是 ViewBag。
我找到了各种关于此的文章 - 但它们似乎都有很大的漏洞 - 例如,这篇文章不涉及编辑,我不明白应该如何或何时使用“SelectedFlavourId”。 http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx
我有几个要求。
- 编辑故事时,我想要一个包含所有地点的下拉列表 被显示 - 与相关的地方(如果有的话) - 被选中。
- 我想使用强类型的 DropDownListFOR(而不是 下拉列表)。
- 我想使用 ViewModel 而不是 ViewBag。
- 我想添加一个“No Associated Place”,它将是 如果 PlaceId 为空,则选中。
- 我想在 DropDownListFor 中添加一个 css class= "form-control"。
以下是我经过一天的挫折后得到的。
可以选择将故事与 PlaceId 关联。空白 placeId 也是有效的。一个地方也可以与多个故事相关联。
模型
public class Place
{
public Guid Id { get; set; }
public string PlaceName { get; set; }
}
public class Story
{
public Guid Id { get; set; }
public Guid? PlaceId { get; set; }
public string StoryName { get; set; }
}
public class StoryPlaceDropdown
{
public Story story { get; set; }
public Guid SelectedStoryId;
public IEnumerable<Place> places;
public IEnumerable<SelectListItem> placeItems
{
get
{
return new SelectList(places, "Id", "PlaceName");
}
}
}
控制器
public ActionResult Edit(Guid Id)
{
var spd = new StoryPlaceDropdown();
spd.places = PlaceRepo.SelectAll();
spd.story = StoryRepo.SelectStory(Id);
spd.selectedStoryID = apd.story.Id;
// Return view
return View(spd);
}
[HttpPost]
public ActionResult Edit(StoryPlaceDropdown spd)
{
// Never gets this far
spd.Places = PlaceRepo.SelectAll();
return View();
}
可见
@Html.DropDownListFor(m => m.SelectedStoryId, Model.PlaceItems)
这很好地填充了 DropDownList。但是,它不会在编辑视图中选择正确的项目。此外,当我提交表单时,我收到此错误: 你调用的对象是空的。在视图中的这一行上 @Html.DropDownListFor(m => m.SelectedStoryId, Model.PlaceItems)
我怎样才能让这一切正常工作?谢谢。
【问题讨论】:
-
@Html.DropDownListFor(m => m.SelectedStoryId, Model.PlaceItems, "No Associated Place", new { @class = "form-control" })来处理最后 2 个点(第 3 个参数添加null标签选项,第 4 个添加类名)。如果SelectedStoryId的值与Place.Id值之一完全匹配,则将选择该选项。 -
至于
NullReferenceException,你需要在你的POST方法中显示代码(我假设你必须尝试访问属性placeItems中的一个值,这将是null)并且有返回视图时未重新填充SelectList。 -
此外,您的模型包含
SelectedStoryId的字段 - 它必须是属性 -public Guid SelectedStoryId { get; set;}才能绑定 -
谢谢 - 这让我在几点上走上了正确的道路 - 结果我忘记了 { get;放; } 模型属性的访问器,但这是主要问题!