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的方法