MVC Scaffolding错误:"值不能为null.参数名称:source"

Gus*_*oTM 5 asp.net-mvc scaffolding html.dropdownlistfor asp.net-mvc-3

我按照这篇文章中的说明进行操作,但是当我尝试添加产品时,我收到此错误:

Server Error in '/' Application.
--------------------------------------------------------------------------------

Value cannot be null.
Parameter name: source 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: source

Source Error: 


Line 63: </div>
Line 64: <div class="editor-field">
Line 65:     @Html.DropDownListFor(model => model.CategoryId, ((IEnumerable<GAM.Models.Category>)ViewBag.PossibleCategories).Select(option => new SelectListItem {
Line 66:         Text = (option == null ? "None" : option.Name), 
Line 67:         Value = option.Id.ToString(),
Run Code Online (Sandbox Code Playgroud)

控制器代码是:

public ActionResult Create()
{
    ViewBag.PossibleCategory = context.Categories;
    return View();
} 

//
// POST: /Product/Create

[HttpPost]
public ActionResult Create(Product product)
{
    if (ModelState.IsValid)
    {
        context.Products.Add(product);
        context.SaveChanges();
        return RedirectToAction("Index");  
    }

    ViewBag.PossibleCategory = context.Categories;
    return View(product);
}
Run Code Online (Sandbox Code Playgroud)

并且视图的代码是:

 @Html.DropDownListFor(model => model.CategoryId, ((IEnumerable<GAM.Models.Category>)ViewBag.PossibleCategories).Select(option => new SelectListItem {
    Text = (option == null ? "None" : option.Name), 
    Value = option.Id.ToString(),
    Selected = (Model != null) && (option.Id == Model.CategoryId)
}), "Choose...")
@Html.ValidationMessageFor(model => model.CategoryId)
Run Code Online (Sandbox Code Playgroud)

完整的代码在这里

Len*_*rri 11

您的问题如下:

您在以下内容中指定此属性Controller:

ViewBag.PossibleCategory = context.Categories;
Run Code Online (Sandbox Code Playgroud)

然后,在您View尝试阅读此动态ViewBag属性:

ViewBag.PossibleCategories
Run Code Online (Sandbox Code Playgroud)

你能看到错误吗?你给出了不同的名字......你没有得到编译时检查,因为ViewBag使用了新的C#4 dynamic类型.ViewBag.PossibleCategories只会在运行时解决.由于没有ViewBag匹配的属性,ViewBag.PossibleCategories您会收到此错误:Value cannot be null. Parameter name: source

要解决这个问题,只需这样做:

ViewBag.PossibleCategories = context.Categories;
Run Code Online (Sandbox Code Playgroud)

  • 非常好抓!我有完全相同的问题,不能为我的生活看到错误. (2认同)