下拉列表将空值发送给后期操作

时间:2013-02-19 14:26:52

标签: asp.net-mvc-3

这是我的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!");
        }

有人可以告诉我为什么吗?

1 个答案:

答案 0 :(得分: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!");
}