gpt4 book ai didi

c# - 使用 CheckBoxListFor Extension 获取 "Value cannot be null"异常

转载 作者:太空宇宙 更新时间:2023-11-03 13:40:51 26 4
gpt4 key购买 nike

我正在从数据库中的引用表中提取值列表,并使用 CheckBoxListFor 将它们显示在我的 MVC4 View 中。现在,初始加载、验证以及将选定值发回 Controller 时一切正常。只有在出于某种原因我的 Controller 触发验证错误并返回到最初发起该帖子的 View 时,我的问题才会发生。

我的 View 模型:

public class DetailsViewModel
{
public ICollection<GoodsType> GoodsType { get; set; }
public ICollection<GoodsType> SelectedGoodsType { get; set; }
public PostedGoodsType PostedGoodsType { get; set; }

public class PostedGoodsType
{
public string[] GoodsTypeIDs { get; set; }
}
}

我的看法:

<ul id="typeOfGoodsCheckBoxList" class="formList botDots twinCols clearfix">
@Html.CheckBoxListFor(model => model.PostedGoodsType.GoodsTypeIDs,
model => model.GoodsType,
entity => entity.GoodsTypeID,
entity => entity.GoodsTypeDesc,
model => model.SelectedGoodsType)
</ul>

我的 Controller :

// This Action is loaded on the first request
public ActionResult DeclareDetails(int? declarationID = null)
{
return View(viewModel);
}

// This action is called on the submit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SubmitDeclareDetails(DetailsViewModel viewModel)
{
var errors = new List<ValidationResult>();
// Validate ViewModel
var command = Mapper.Map<Declaration, CreateOrUpdateDeclarationCommand>(viewModel.Declaration);
errors = _commandBus.Validate(command).ToList();
// Add the custom errors to the modelstate
ModelState.AddModelErrors(errors);
if (ModelState.IsValid)
{
var result = _commandBus.Submit(command);
if (result.Success)
{
return RedirectToAction("DeclareVehicle", viewModel);
}
}
// If something went wrong, go back to the page and display the errors
return View("DeclareDetails", viewModel);
}

当我收到验证错误并且我的 ModelState.IsValid 为假时,我想返回到初始 View ,传递 ViewModel 但我收到此错误:

值不能为空。参数名称:source

描述:当前网络请求执行过程中出现未处理的异常。请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。

异常详细信息:System.ArgumentNullException:值不能为空。参数名称:source

来源错误:

Line 296:                    </legend>
Line 297: <ul id="typeOfGoodsCheckBoxList" class="formList botDots twinCols clearfix">
Line 298: @Html.CheckBoxListFor(model => model.PostedGoodsType.GoodsTypeIDs,
Line 299: model => model.GoodsType,
Line 300: entity => entity.GoodsTypeID,

我尝试在创建 ViewModel 时初始化对象,但没有成功。有什么想法吗?

预先感谢您的帮助!

最佳答案

感谢 Rikon 对 OP 的评论,我已经设法找出问题所在。我的问题是我在同一 View 中有 3 个不同的实体(引用表)使用 CheckBoxListFor,其中 2 个是互斥的。

因此,每当我回发时,这 3 个实体中的一个始终为 null,因此当我回发时,该实体为 null 并抛出上述异常。

解决方案是简单地初始化 CheckBoxListFor 中使用的对象,即使我不使用它们也是如此。这样,它们将始终绑定(bind)到模型并可以来回传递。

public SelfDeclareOperatorDetailsViewModel()
{
GoodsType = new List<GoodsType>();
SelectedGoodsType = new List<GoodsType>();
PostedGoodsType = new PostedGoodsType { GoodsTypeIDs = new string[0] };
}

再次感谢大家!

关于c# - 使用 CheckBoxListFor Extension 获取 "Value cannot be null"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17093163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com