无法对空引用执行运行时绑定,但它不是空引用
本文关键字:引用 运行时 执行 绑定 | 更新日期: 2023-09-27 18:35:55
>使用: MVC 4, ASP.NET Razor
我收到一个错误,看起来不可能。它告诉我我正在使用空引用,状态,但显然它正在设置。
控制器:
public ActionResult Index()
{
Dictionary<int, string> states = new Dictionary<int, string>()
{
{ -1, "a"},
{ 0, "b"},
{ 1, "c"},
{ 2, "d"},
};
//assigning states
ViewBag.States = states;
foreach (KeyValuePair<int, string> de in ViewBag.States)
{
Debug.WriteLine(de.Key);
}
return View();
}
观点:
<div class="search-input">
<select>
@foreach (KeyValuePair<int, string> de in ViewBag.States)
{
<option value="@de.Key">@de.Value</option>
}
</select>
</div>
错误:
Cannot perform runtime binding on a null reference
Line 54: @foreach (KeyValuePair<int, string> de in ViewBag.States)
找到解决方案:我的观点中有拼写错误,ViewBag.Typo <- 这导致了错误,但调试器将异常放在不相关的地方。
当您的 razor 代码中存在 ViewBag 不存在调用方法时,会发生此错误。
控制器
public ActionResult Accept(int id)
{
return View();
}
剃刀:
<div class="form-group">
@Html.LabelFor(model => model.ToId, "To", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Flag(Model.from)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input value="@ViewBag.MaximounAmount.ToString()" />@* HERE is the error *@
</div>
</div>
由于某种原因,.net 无法在正确的行中显示错误。
通常,这会导致大量时间浪费。
当使用
反射动态更新不存在的属性时,也会引发此异常。
如果使用反射动态更新属性值,则值得检查以确保传递的PropertyName
与实际属性相同。
就我而言,我试图更新Employee.firstName
,但该物业实际上是Employee.FirstName
。
值得记住。:)
我对此错误的解决方案是从另一个引用@Model.Id
的项目复制和粘贴。这个特定的页面没有模型,但错误线与实际错误相去甚远,我几乎没有找到它!
必须定义不等于 null 的状态。
@if (ViewBag.States!= null)
{
@foreach (KeyValuePair<int, string> de in ViewBag.States)
{
value="@de.Key">@de.Value
}
}
与 Razor 无关,您将在运行时尝试访问动态值中的"不存在"属性中看到该异常:
dynamic myValue;
if(myValue.notExistedProperty == "some-value") { ... }
Set
Dictionary<int, string> states = new Dictionary<int, string>()
作为函数外部和函数内部插入条目的属性,它应该可以工作。