0

どうか私に答えてください!私はいつもこの問題を抱えています!これは私のコントローラーです:

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>

カテゴリを投稿アクションにバインドするにはどうすればよいですか。ページを送信した後、「キー 'categoryId' を持つタイプ 'IEnumerable' の ViewData アイテムはありません」というエラーが発生しました。だから私は何をすべきですか?

4

1 に答える 1

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>
于 2013-02-28T13:34:25.800 に答える