我正在做一个项目,涉及到在ASP.Net Core 7.0中使用select选项,我遇到了一些困难。具体来说,我在下拉列表中遇到了与空引用异常相关的错误。但是我观察到,提交数据后,安装到SQL数据库中,提交后返回时,显示空引用异常错误。这些错误使开发过程变得相当具有挑战性,我希望尽快找到解决方案。任何意见或建议将不胜感激。
错误
行动
public IActionResult Apply()
{
ViewBag.Courselist = new SelectList(GetAllAccountIDList(), "Id",
"CourseName");
return View();
}
[HttpPost]
public IActionResult Apply(PurchasedFormViewModel purchasedFormVM)
{
if (ModelState.IsValid)
{
try
{
var transaction = new StudentBiodataViewModels
{
CourseId = purchasedFormVM.CourseId,
SurName = purchasedFormVM.SurName,
OtherName = purchasedFormVM.OtherName,
PhoneNumber = purchasedFormVM.PhoneNumber,
Email = purchasedFormVM.Email,
};
_context.StudentBiodata.Add(transaction);
_context.SaveChangesAsync();
}
catch (Exception ex)
{
ViewBag.Message = ex.Message + " Error occur while inserting records.";
}
}
return View();
}
楷模
public class ApplyFormViewModel
{
public int Id { get; set; }
[Display(Name = "Course Apply")]
[Required(ErrorMessage = "Course Apply is Required")]
public int CourseId { get; set; }
[Display(Name = "SurName")]
[Required(ErrorMessage = "SurName is Required")]
public string SurName { get; set; }
[Display(Name = "Other Name")]
[Required(ErrorMessage = "Other Name is Required")]
public string OtherName { get; set; }
[Display(Name = "Phone Number")]
[Required(ErrorMessage = "Phone Number is Required")]
ErrorMessage = "Entered phone format is not valid.")]
public string PhoneNumber { get; set; }
[Required(ErrorMessage = "Email is Required")]
public string Email { get; set; }
}
看法
<select id="fundcode" asp-for="CourseId" class="form-control">
<option value="">--Please select--</option>
@foreach (var item in ViewBag.Courselist )
{
<option value="@item.Value">@item.Text</option>
}
</select>
您将从 POST 返回到 GET 处理程序中调用的同一视图,但未设置ViewBag.CourseList。当然,当页面呈现时,该变量为 NULL,并且您会得到异常。
我认为您需要在返回到 Post 处理程序内的 View 之前添加 GET 中使用的相同代码