我有一个MVC 5网站,我想使用强类型的DropDownListFor与ViewModel - 而不是与ViewBag。asp.net mv 5,DropDownListFor与ViewModel不能正常工作
我发现了各种各样的文章 - 但他们似乎都有巨大的漏洞 - 例如这一个不包括编辑,我不明白如何或何时应该使用“SelectedFlavourId”。 http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx
我有几个要求。
- 当编辑的故事,我想一个下拉的所有地方 的列表中显示 - 与相关地点(如果有的话) - 选择。
- 我想使用强类型DropDownListFOR(而不是 DropDownList)。
- 我想使用ViewModel而不是ViewBag。
- 我想添加一个“No Associated Place”,如果PlaceId为null,那么将会选择 。
- 我想添加一个css class =“form-control”到DropDownListFor。
以下是就我经历了一天的挫折之后所得到的。
故事可以选择与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)
这将填充DropDow nList很好。但是,它不会在编辑视图中选择正确的项目。另外,当我提交表单时,出现此错误: 未将对象引用设置为对象的实例。在视图@ Html.DropDownListFor(m => m.SelectedStoryId,Model.PlaceItems)的这一行上
我该如何得到这一切?谢谢。
第1步:创建视图模型
public class StoryPlaceDropdown
{
Required]
[Display(Name = "SelectedStory")]
public int SelectedStoryId { get; set; }
}
第2步:这对控制器之后,你可以写:
public ActionResult Edit(Guid Id)
{
var spd = new StoryPlaceDropdown();
ViewBag.PlaceItems= PlaceRepo.SelectAll();
spd.story = StoryRepo.SelectStory(Id);
spd.selectedStoryID = apd.story.Id;
return View(spd);
}
步骤3
'@Html。DropDownListFor(m => m.SelectedStoryId,Model.PlaceItems,“No Associated Place”,new {@class =“form-control”})'解决最后2个点的点(第三个参数添加一个'null'标签选项,第四个添加类名)。如果'SelectedStoryId'的值恰好匹配'Place.Id'值之一,那么将选择该选项。 –
至于'NullReferenceException',你需要在你的POST方法中显示代码(我假设你必须试图访问属性'placeItems'中的一个值,它将是'null'),并且在'SelectList'时没有重新填充你返回视图。 –
另外你的模型包含一个'SelectedStoryId'的字段 - 它需要是一个属性 - 'public Guid SelectedStoryId {get;设置;}'为了绑定 –