我有一个ASP.NET MVC应用程序。当我试图输入包含表单的视图(剃刀页)时,我会得到以下错误:
处理请求时发生了未处理的异常。SqlNullValueException:数据是空的。不能对空值调用此方法或属性。
注意:当我试图发送表单时,我没有收到错误,而是当我输入包含表单的视图(剃刀页)时。
只有当我转到模型并给string属性一个[Required]数据注释标记时,才会出现此错误。如果我删除标记,它就能工作(没有验证ofc)
public class Category
{
[Key]
public int CategoryId { get; set; }
[Required]
public string Name { get; set; }
[DisplayName("Display Order")]
[Required]
[Range(1, int.MaxValue, ErrorMessage = "Display Order For category must be greater than 0")]
public int DisplayOrder { get; set; }
}编辑:Name属性导致错误
我的问题是:为什么当我输入页面时显示错误,而不是在发送带有空白Name属性的表单时显示错误?简而言之,为什么我会得到这个错误?
剃刀页代码是:
@model IEnumerable<MVCtesting01.Models.Category>
<div class="container p-3">
<div class="row pt-4">
<div class="col-6">
<h2 class="text-primary">Category List</h2>
</div>
<div class="col-6 text-right">
<a asp-controller="Category" asp-action="Create" class="btn btn-primary">Create New Category</a>
</div>
</div>
<br /><br />
@if(Model.Count() > 0)
{
<table class="table table-bordered table-striped" style="width100%">
<thead>
<tr>
<th>
Category Name
</th>
<th>
Display Order
</th>
<th>
Buttons
</th>
</tr>
</thead>
<tbody>
@foreach(var obj in Model)
{
<tr>
<td width="50%">@obj.Name</td>
<td width="30%">@obj.DisplayOrder</td>
<td class="text-center">
<div class="w-75 btn-group" role="group">
<a asp-controller="Category" asp-route-Id="@obj.CategoryId" asp-action="Edit" class="btn btn-primary">Edit</a>
<a asp-controller="Category" asp-route-Id="@obj.CategoryId" asp-action="Delete" class="btn btn-danger">Delete</a>
</div>
</td>
</tr>
}
</tbody>
</table>
}
else
{
<p>No category exists.</p>
}
</div>错误出现在第15行: AspNetCore.Views_Category_Index.ExecuteAsync() in Index.cshtml
@if(Model.Count() > 0)发布于 2021-10-02 23:31:41
你的模型是空的,你没有发送任何。添加一些validatiton,它将修复异常。
@if( Model!=null && Model.Count() > 0)
.....由于您使用的是循环i,因此强烈建议您将模型更改为此,如果需要,它将允许您提交数据。
@model List<MVCtesting01.Models.Category>如果您想知道如何创建正确的模型,请张贴您的操作。
https://stackoverflow.com/questions/69420842
复制相似问题