我正在处理一个涉及ASP.NET Core 7.0中SELECT选项的使用的项目,我遇到了一些困难.具体地说,我在下拉列表中遇到了与空引用异常相关的错误.然而,我观察到,提交数据后,它被安装到SQL数据库中,提交后返回时,显示空引用异常错误.这些错误使开发过程变得非常具有挑战性,我希望尽快找到解决方案.如有任何意见或建议,将不胜感激.

Error

enter image description here

Action

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

Models

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

View

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

推荐答案

  • Ensure Dropdown Population:验证GetAllAccount tIDList()方法是否返回ID值非空值的有效项列表 和CourseName属性.如果任何项为空,或者如果 List本身为空,在绑定下拉列表时可能会导致问题 在视图中.
  • Check ModelState Validation:在POST操作中访问PurchasedFormVM对象的属性之前,请确保 ModelState有效.如果缺少任何必填字段,或者如果 都是验证错误,则ModelState可能无效,从而导致 传递给操作的空值.
  • Save Changes Synchronously:在POST操作中,您使用_context.SaveChangesAsync()将更改保存到数据库.但是,此方法返回一个任务,因此您应该等待它,以确保 更改将正确保存.否则,该方法可能会在 更改实际上已保存,可能会导致问题.
[HttpPost]
public async Task<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);
            await _context.SaveChangesAsync(); // Await SaveChangesAsync
        }
        catch (Exception ex)
        {
            ViewBag.Message = ex.Message + " Error occur while inserting records.";
        }
    }
    // Repopulate ViewBag.Courselist in case of validation errors
    ViewBag.Courselist = new SelectList(GetAllAccountIDList(), "Id", "CourseName");
    return View();
}

Csharp相关问答推荐

使用C#中的Shape API从Azure目录获取所有用户

如何使用C#中的图形API更新用户配置文件图像

NumPy s fftn in C#with pythonnet'

如何在Windows 11任务调度程序中每1分钟重复一次任务?

方法从数据表中只 Select 一个条件?

当前的文化决定了错误的文化

异步任务导致内存泄漏

将字节转换为 struct 并返回

Lambda表达式如何与隐式强制转换一起工作?

RX操作员使用先前值进行扫描,信号来自值本身

为什么我的伺服电机不动,下面的代码?

在';、';附近有错误的语法.必须声明标量变量";@Checkin";.';

使用ASP.NET MVC for Lemon Squeezy X-Signature创建散列

如何在特定环境中运行dotnet测试?

C#静态抽象属性不能被子接口覆盖

工厂类是如何在.NET 8中注册的?

ASP.NET核心中的授权,如何在DbContext启动之前提供租用ID

使用LibraryImport在多个dll中导入相同的函数

如何将行添加到DataGrid以立即显示它?

初始化具有EntityFrameworkCore和不同架构的数据库时引发System.MissingMethodExcept