2013-02-21 41 views
0

請給我一些答案!我總是有這個麻煩! 這是我的控制器:將一個SelectList值綁定到Post Action

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> 

現在我怎樣才能綁定類別才能發佈行動,提交頁面後,我得到這個錯誤: 「沒有的ViewData具有'categoryId'鍵的'IEnumerable'類型的項目。 那我該怎麼辦?你是以下

回答

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>