0

这是我的 Get actionresult :

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

            return View("Add");
        }

这是我呈现 categoryList 的剃须刀,我对此没有任何问题!

<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!");
        }

谁能告诉我为什么?

4

1 回答 1

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!");
}
于 2013-02-19T14:30:00.747 回答