MVC Scaffolding错误:“值不能为null。参数名称:source”

时间:2011-06-06 03:20:33

标签: asp.net-mvc asp.net-mvc-3 html.dropdownlistfor scaffolding

我按照此post中的说明操作,但当我尝试添加产品时出现此错误:

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(),

控制器代码为:

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

视图的代码是:

 @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)

完整代码为here

2 个答案:

答案 0 :(得分:11)

您的问题如下:

您在Controller

中分配此属性
ViewBag.PossibleCategory = context.Categories;

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

ViewBag.PossibleCategories

你能看到错误吗?你给出了不同的名字......你没有得到编译时检查,因为ViewBag使用了新的C#4 dynamic typeViewBag.PossibleCategories只会在运行时解析。由于没有匹配ViewBag的{​​{1}}属性,因此出现此错误:ViewBag.PossibleCategories

要解决这个问题,请执行以下操作:

Value cannot be null. Parameter name: source

答案 1 :(得分:0)

我在使用 EF Core 5 和 MVC 的 .NET 5 (.NET Core) 中收到此错误。

Value cannot be null. Parameter name: connectionString

问题是我没有 appsettings.json 文件,因此没有数据库的连接字符串,所以脚手架无法连接到数据库。