2013-02-19 52 views
0

這是我獲取的ActionResult:下拉列表中發送空值後動作

public ActionResult Add() 
     { 
      ViewData["categoryList"]= _categoryRepository.GetAllCategory(). 
      ToSelectList(c => c.Id, c => c.Name); 

      return View("Add"); 
     } 

這是我的剃鬚刀渲染所屬分類,和我有沒有麻煩!

<div> 
     @Html.LabelFor(b => b.Category) 
     @Html.DropDownList("Category", ViewData["categoryList"] as IEnumerable<SelectListItem>) 
     @Html.ValidationMessageFor(b => b.Category) 
    </div> 

最後提交頁面後,選擇類通過空值發送到發佈此動作

 [HttpPost] 
     public ActionResult Add(BlogPost blogPost) 
     { 
      if (ModelState.IsValid) 
      { 
       blogPost.PublishDate = DateTime.Now; 

       _blogPostRepository.AddPost(blogPost); 

       _blogPostRepository.Save(); 
       return RedirectToAction("Add"); 
      } 
      return new HttpNotFoundResult("An Error Accoured while requesting your    order!"); 
     } 

可能有人告訴我爲什麼?

回答

1

控制器

public ActionResult Add() 
{ 
    ViewBag.CategoryList = new SelectList(_categoryRepository.GetAllCategory(), "Id", "Name"); 

    // you dont need the specify View name 
    // like this: return View("Add") 
    // you need to pass your model. 
    return View(new BlogPost()); 
} 

視圖

@Html.DropDownListFor(model => model.CategoryId, ViewBag.CategoryList as SelectList, "--- Select Category ---", new { @class = "some_class" }) 

控制器後行動

[HttpPost] 
public ActionResult Add(BlogPost blogPost) 
{ 
    if (ModelState.IsValid) 
    { 
     blogPost.PublishDate = DateTime.Now; 

     _blogPostRepository.AddPost(blogPost); 

     _blogPostRepository.Save(); 

     // if you want to return "Add" page you should 
     // initialize your viewbag and create model instance again 
     ViewBag.CategoryList = new SelectList(_categoryRepository.GetAllCategory(), "Id", "Name"); 
     return View(new BlogPost()); 
    } 
    return new HttpNotFoundResult("An Error Accoured while requesting your    order!"); 
} 
+0

謝謝您的回答,但我沒有任何麻煩,發送類別列表來查看,主要問題是選擇的類別劑量未發送到發佈操作... – 2013-02-19 14:43:05

+0

因爲您不綁定它模擬。通過它來查看是不夠的,你應該把它模型化。如果你不想使用我的建議,你應該添加一個額外的屬性到你的postAction中,如下所示:'public ActionResult Add(BlogPost blogPost,string Category)' – 2013-02-19 14:46:07

+0

有關於你的BlogSpot和類別列表的關係,所以我的建議是更好的StroglyTyped邏輯的方式。 – 2013-02-19 14:47:23