jquery 单击提交按钮后显示错误对象引用未设置为对象的示例,在Model.userModel.branches上?

ubof19bj  于 2023-05-17  发布在  jQuery
关注(0)|答案(1)|浏览(131)

我工作在MVC剃刀页asp.net核心7。我不能显示成功消息后提交和插入数据在同一页上。
我得到错误

System.NullReferenceException: 'Object reference not set to an instance of an object.'

错误发生在Model.userModel.Branches上
预期结果是在插入数据成功但点击提交按钮后显示成功消息
数据插入并给予我这个错误空引用异常
那么如何解决这个错误呢?

public class AddUserModel : PageModel
    {
        [BindProperty]
        public AddUserViewModel userModel { get; set; }
        [BindProperty]
        public UC.ADC.Core.Entities.SQL.User  User { get; set; }
        public string SuccessMessage { get; set; }
public AddUserModel(ADCContext db,OracleContext ora_db2)
        {
            
             _db = db;
            userModel = new AddUserViewModel();
        }
     public async Task<IActionResult> OnPost()
            {
                if (ModelState.IsValid)
                {
                    await _db.User.AddAsync(User);
                    await _db.SaveChangesAsync();
                    SuccessMessage = "Form submitted successfully!";
                    return Page();
                    
    
                }
                
            }
    public void OnGet()
            {
                userModel.Branches  = _db.Branch.ToList();
             }
  }

在adduser.cshtml上

@page "/AddUser"
<form method="post">
       

        <div class="form-group row">
            <label for="branch-select" class="col-sm-1 col-form-label" style="font-size:15px;font-family: 'Open Sans', sans-serif;font-weight: bold;">Branch</label>
            <div class="col-sm-3">
                <select id="branch-select" asp-for="User.iBranchCode" class="form-control" style=" margin-left:10px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;">
                    <option value="">-- Select Branch --</option>
                 
                     @foreach (var branch in Model.userModel.Branches)
                    {
                        <option value="@branch.iBranchCode">@branch.vBranchDesc</option>
                    }
                </select>
            </div>
        </div>
<div class="form-group row" style="margin-left:200px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;">
            <button type="submit" class="col-sm-1 btn btn-primary">Submit</button>
           
        </div>
</form
xurqigkl

xurqigkl1#

HTTP是无状态的,这意味着在一个请求中生成的数据不会持久化。在您的例子中,GET请求中生成的分支在POST请求中不可用,需要在那里重新生成:

public async Task OnPost()
{
    userModel.Branches  = _db.Branch.ToList(); // generate the branches
    if (ModelState.IsValid)
    {
        await _db.User.AddAsync(User);
        await _db.SaveChangesAsync();
        SuccessMessage = "Form submitted successfully!";
     }
}

相关问题