我拉我的头发试图让下拉列表中我的剃刀视图的工作,我无法找到一个可行的解决方案,我只能假设我失去了一些东西明显..DropDownListFor总是空的回发
我正在尝试创建一个注册页面,其中包含使用文本框(正常工作)和下拉列表从查找表中选择项目并将该项作为外键插入到我的新记录中的学生的个人详细信息。所以,我的学生有一个标题 - 我填充下拉列表中的所有Salutations & ID从我的数据库中,允许用户选择一个,然后保存这与我的新学生记录回发给控制器。下拉列表填充正常,值都在那里,用户可以选择一个值,但在回发时它总是为空?
下面给出的例子涉及到我的模型中只有一个这样的领域,有很多。在试图让它起作用时,我使用了所有的文本框,并且只使用了一个下拉框,所以问题在某处,而不是隐藏在其他代码中。
我的模型(ViewCandidate)有(与其他字段一起):
public int SalutationID {get; set;}//foreign key to be saved when I pass the values from my View object to a domain entity object
public Dictionary<int, string> Salutations {get; set;} //key/value pairs to fill the dropdown in the view
当我创建控制器的型号我填写像这样的下拉菜单:
public ViewResult Link()
{
return View(new ViewCandidate{ Salutations = GetSalutations(entities) }); //'entities' is my Entity Framework context, all the entities in my data model/database
}
public static Dictionary<int, string> GetSalutations(DBEntities entities)
{
Dictionary<int, string> dictionary = new Dictionary<int, string>();
foreach(var s in entities.Salutations)
{
dictionary.Add(s.SalutationID, s.Salutation);
}
return dictionary;
}
在我的剃须刀查看我使用的模型绑定是这样的:
@model ViewModels.ViewCandidate
...
<div class="align-center">
<label>Title</label>
@Html.DropDownListFor(x => x.SalutationID, new SelectList(Model.Salutations, "Key", "Value"), "Please select your title", new { @class="form-control"})
</div>
当我运行应用程序并导航到链接控制器页面这是为下拉菜单生成的html:
<div class="align-center">
<label>Title</label>
<select class="form-control" data-val="true" data-val-number="The field SalutationID must be a number." data-val-required="The SalutationID field is required." id="SalutationID" name="SalutationID"><option value="">Please select your title</option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Miss</option>
<option value="4">Ms</option>
<option value="5">Master</option>
<option value="6">Doctor</option>
</select>
</div>
使用正确的值生成下拉菜单就好了。但是,当我填写表格的其余部分,并提交后回来,我带回到这里在Visual Studio(从我的Razor视图行):
@Html.DropDownListFor(x => x.SalutationID, new SelectList(Model.Salutations, "Key", "Value"), "Please select your title", new { @class="form-control"})
,出现以下错误:
An exception of type 'System.ArgumentNullException' occurred in System.Web.Mvc.dll but was not handled in user code
Value cannot be null.
Parameter name: items
'Items'是SelectList构造函数中IEnumerable的参数名称,它具有项目并已全部呈现它们。在我的数据库中或在视图中呈现的salutation记录都不为NULL。我无法得到这个工作,它让我发疯,任何人都可以帮忙?
如果它有什么区别我正在使用实体框架 - 所以我最终保存的实体是'Candidate',我将ViewCandidate中的值传递给视图中创建的值。我重复创建Dictionary<int, string>
的礼物是EF对象。在View对象中包装这些也没有帮助。
当您返回视图时,您需要重新分配Model.Salutations的值(由于Salutations为空而出现错误) – 2015-02-08 21:11:04