请和我一起回答一些问题!我一直都有这个麻烦! 这是我的控制器:
public ActionResult Create()
{
IEnumerable<SelectListItem> items =
_categoryService.GetAllCategory().Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Name
});
ViewBag.Categories = items;
return View();
}
[HttpPost]
public ActionResult Create(ProductViewModel productViewModel,Guid categoryId)
{
if (ModelState.IsValid)
{
_productService.Create(productViewModel);
}
return View();
}
这是我的观点:
@model Statos.Service.Products.ProductViewModel
@{
ViewBag.Title = "Create";
}
<fieldset>
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(product => product.Name)
@Html.TextBoxFor(Product => Product.Name)
</div>
<div>
@Html.LabelFor(product => product.Brand)
@Html.TextBoxFor(product => product.Brand)
</div>
<div>
@Html.LabelFor(product => product.Category)
@Html.DropDownList("categoryId", (IEnumerable<SelectListItem>)ViewBag.Categories)
</div>
<div>
@Html.LabelFor(product => product.Price)
@Html.TextBoxFor(product => product.Price)
</div>
<div>
@Html.LabelFor(product => product.Description)
@Html.TextBoxFor(product => product.Description)
</div>
<div>
<input type="submit" value="Add" />
</div>
}
</fieldset>
现在如何将类别绑定到后期操作,在提交页面后我收到此错误: “没有类型'IEnumerable'的ViewData项具有键'categoryId'”。 所以我该怎么做 ?
答案 0 :(得分:0)
您关注的流程不正确 以下是它在控制器中的外观,这来自我当前正在运行的项目
public ActionResult Create()
{
var model = new UserCreateViewModel
{
Roles = new SelectList(GetRoles(), "Id", "Name"),
Ranks = new SelectList(GetRanks(), "Id", "Name")
};
return View(model);
}
在视图中它会有点像这样
<div class="control-group">
<div class="controls">
<div class="editor-label span4 pull-left nomargin">
@Html.LabelFor(m => m.Roles)
</div>
<div class="editor-field">
@Html.DropDownListFor(m => m.User.RoleId, @roles, Index.SelectRole)
@Html.ValidationMessageFor(m => m.User.RoleId)
</div>
</div>
</div>