错误Razor

An unhandled exception occurred while processing the request.

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

报错是这样

考虑错误原因,传参存在错误

确保传参的正确性

 措施:

1.检查页面传参。Page上面的{id}代表传参  Edit.cshtml代码如下

@page "{id}"
@model RazorPagesTutorial.Pages.Employees.EditModel
@{
    ViewData["Title"] = "Edit";
    var photoPath = "~/images/" + (Model.Employee.PhotoPath ?? "noimage.jpg");
}


<h1>Notification Preferences</h1>

<form method="post" asp-page-handler="UpdateNotificationPreferences">
    <input hidden asp-for="Employee.Id" />
    <div class="form-check">
        <input asp-for="Notify" class="form-check-input" />
        <label asp-for="Notify" class="form-check-label">
            Receive email notification when my details change
        </label>
    </div>
    <button type="submit" class="btn btn-primary">
        Update Notification Preferences
    </button>
    @if (!string.IsNullOrEmpty(Model.Message))
    {
        <div class="alert alert-primary">
            @Model.Message
        </div>
    }
   
</form>

<hr/>


<h1>Edit</h1>
<form method="post" class="mt-3" enctype="multipart/form-data" asp-page-handler="OnPost">
    <input hidden asp-for="Employee.Id" />
    <input hidden asp-for="Employee.PhotoPath" />
    <div class="form-group row">
        <label asp-for="Employee.Name" class="col-sm-2 col-form-label">

        </label>

        <div class="col-sm-10">
            <input asp-for="Employee.Name" class="form-control" placeholder="Name" />
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="Employee.Email" class="col-sm-2 col-form-label">

        </label>

        <div class="col-sm-10">
            <input asp-for="Employee.Email" class="form-control" placeholder="Email" />
        </div>
    </div>

    <div class="form-group row">
        <label asp-for="Employee.Department" class="col-sm-2 col-form-label">

        </label>
        <div class="col-sm-10">
            <select asp-for="Employee.Department" class="custom-select mr-sm-2"
            asp-items="Html.GetEnumSelectList<Dept>()">
                <option value="">Please Select</option>
            </select>
        </div>
    </div>

    <div class="form-group row">
        <label asp-for="Photo" class="col-sm-2 col-form-label">
        </label>
        <div class="col-sm-10">
            <div class="custom-file">
                <input asp-for="Photo" class="custom-file-input form-control" />
                <label class="custom-file-label">Click here to change photo</label>
            </div>
        </div>
    </div>

    <div class="form-group row col-sm-4 offset-4">
        <img class="imageThunbnail" src="@photoPath" asp-append-version="true"/>
    </div>

    <div class="form-group row">
        <div class="col-sm-10">
            <button type="submit" class="btn btn-primary">Update</button>
            <a asp-page="/Employees/Index" class="btn btn-primary">Cancle</a>
        </div>
    </div>

  @*  @section Scripts{
        <script>
            $(document).ready(function(){
                $('.custom-file-input').on("change",function(){
                    var fileName=$(this).val().split("\\").pop();
                    $(this).next('.custom-file-label').html(fileName);
                });
            });
        </script>
    }*@
</form>

2.确保handler向页面传参了下面代码的return,给页面返回了参数id

        public IActionResult OnPostUpdateNotificationPreferences(int id)
        {
            if (Notify)
            {
                Message = "Thank you for turning on notifications";
            }
            else
            {
                Message= "You have turned off email notifications";
            }


            //Employee=employeeRepository.GetEmployee(id);
            //return RedirectToPage("Details", new {id=id,message=Message});

            TempData["message"] = Message;
            return RedirectToPage("Details", new { id = id });
        }

Edit.cshtml.cs完整代码

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPagesTutorialModels;
using RazorPagesTutorialServices;
using static System.Net.Mime.MediaTypeNames;

namespace RazorPagesTutorial.Pages.Employees
{
    public class EditModel : PageModel
    {
        private readonly IEmployeeRepository employeeRepository;
        private readonly IWebHostEnvironment webHostEnvironment;

        //先访问构造函数
        public EditModel(IEmployeeRepository employeeRepository,IWebHostEnvironment webHostEnvironment) { 
            this.employeeRepository = employeeRepository;
            this.webHostEnvironment = webHostEnvironment;
        }

        public Employee Employee { get; set; }
        //访问OnGet方法,此方法判断是否能查询到信息,重定向到不同的页面

        [BindProperty]
        public IFormFile Photo { get; set; }

        [BindProperty]
        public bool Notify { get; set; }

        public string Message { get; set; }
        public IActionResult OnGet(int id)
        {
            Employee=employeeRepository.GetEmployee(id);
            if(Employee == null)
            {
                return NotFound();
            }
            //进入Edit的页面
            return Page();

        }

        public IActionResult OnPostUpdateNotificationPreferences(int id)
        {
            if (Notify)
            {
                Message = "Thank you for turning on notifications";
            }
            else
            {
                Message= "You have turned off email notifications";
            }


            //Employee=employeeRepository.GetEmployee(id);
            //return RedirectToPage("Details", new {id=id,message=Message});

            TempData["message"] = Message;
            return RedirectToPage("Details", new { id = id });
        }

        //进入Edit的页面后
        public IActionResult OnPost(Employee employee) 
        {
            if(Photo != null)
            {
                if(employee.PhotoPath!=null)
                {
                    string filePath = Path.Combine(webHostEnvironment.WebRootPath,"images",employee.PhotoPath);
                //    System.IO.File.Delete(filePath);

                }
                employee.PhotoPath = ProcessUploadedFile();
            }
            Employee=employeeRepository.Update(employee);
            return RedirectToPage("Index");
        }

        private string ProcessUploadedFile()
        {
            string uniqueFileName = null;

            if(Photo!=null)
            {
                string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");
          
            uniqueFileName = Guid.NewGuid().ToString()+"_"+Photo.FileName;
                string filePath=Path.Combine(uploadsFolder,uniqueFileName);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    Photo.CopyTo(fileStream);
                }
            }
            return uniqueFileName;
        }
    }
}

注意:上面中面

<form method="post" asp-page-handler="UpdateNotificationPreferences">

调用的是OnPostUpdateNotificationPreferences的方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值