我一直在讨论如何处理这种情况。我有一个模型,项目模型,它有许多项目需要下拉,以便用户更改所选的项目。我从ProjectType值开始简单,它应该具有从ProjectTypes表填充的可选值。这是ViewModel:
public class ProjectViewModel
{
public APT_Projects Project { get; set; }
public System.Linq.IQueryable<APT_ProjectTypes> projecttypes { get; set; }
public APT_ClientTypes ClientTypes {get; set;}
}
这是控制器:
public ActionResult Edit(int id = 0)
{
APT_Projects apt_projects = db.APT_Projects.Find(id);
if (apt_projects == null)
{
return HttpNotFound();
}
ProjectViewModel Project = new ProjectViewModel();
var apt_projecttypes = from a in db.APT_ProjectTypes
select a;
Project.Project = apt_projects;
Project.projecttypes = apt_projecttypes;
return View(Project);
}
最后是观点:
@model APTII_MVC.ViewModel.ProjectViewModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>APT_Projects</legend>
<div class="editor-label" style="float: left; width: 500px;" >
@Html.LabelFor(model => model.Project.Project_ID)
</div>
<div class="editor-field" style="float: left; width: 500px;" >
@Html.EditorFor(model => model.Project.Project_ID)
@Html.ValidationMessageFor(model => model.Project.Project_ID)
</div>
<div class="editor-label"">
@Html.LabelFor(model => model.Project.ProjectType_ID)
</div>
<div class="editor-field"">
@Html.DropDownListFor(model => model.Project.ProjectType_ID, Model.projecttypes)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
当我以这种方式执行此操作时,.net不喜欢Drowpdownlistfor,但我不清楚如何以dropdownlistfor接受的方式使用这些值。我的错是什么?
编辑:下拉列表的相关错误。
'System.Web.Mvc.HtmlHelper<ViewModel.ProjectViewModel>' does not contain a definition for 'DropDownListFor' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>)' has some invalid arguments c:\Visual Studio 2012\Projects\Test_MVC\Test_MVC\Views\Project\Edit.cshtml
答案 0 :(得分:1)
您可能需要List<SelectListItem>
或SelectList()
..因此请尝试将projecttypes
对象转换为
@Html.DropDownListFor(model => model.Project.ProjectType_ID, new SelectList(Model.projecttypes,"ID","Type")
或将您的viewmodel编辑为
public SelectList projecttypes { get; set; }
和您的控制器代码
Project.projecttypes = new SelectList(db.APT_ProjectTypes,"ID","Type");
只是猜测你的价值/文字字段名称