我正在尝试验证用户提供给用户历史记录的输入,并根据验证结果显示消息。我一直收到System.NullReferenceException:错误,尽管对象引用设置为对象的实例。
我正在处理剃须刀页面。这是C#代码:
public class ConfirmModel : PageModel
{
public CUser User { get; set; }
private readonly IHostingEnvironment _env;
private readonly CDataContext _context;
private readonly IUserService _UserService;
public ConfirmModel(IUserService UserService, CDataContext context, IHostingEnvironment IHostingEnvironment)
{
_env = IHostingEnvironment;
_context = context;
_UserService = UserService;
User = UserService.GetUser();
}
public IList<CPreference> Pref { get; set; }
public IList<CHistory> Hist { get; set; }
public IList<COffers> Off { get; set; }
public IList<CStudent> student{ get; set; }
public ActionResult OnGet()
{
if (User.Role != Role.Admin && User.Role != Role.Student)
{
return RedirectToPage("/Denied");
}
Hist = _context.History.ToList();
Off = _context.Offers.ToList();
Pref = _context.Preference.ToList();
student = _context.Student.ToList();
checkHistory();
return Page();
}
public bool NotInHistory(Courscategory cocat, CStudent stud)
{
bool var_ = false;
foreach (var item in stud.courshistory)
{
if(item == cocat)
{
var_ = true;
}
}
return var_;
}
public void checkHistory()
{
foreach(var item in student)
{
while(!item.is_accepted)
{
foreach(var hist_item in Pref)
{
if(!NotInHistory(hist_item.Category_One, item) && !NotInHistory(hist_item.Category_two, item) && !NotInHistory(hist_item.Category_Three, item))
{
General.AddPreference = false;
}
else
{
General.AddPreference = true;
}
}
}
}
}
public async Task<IActionResult> OnPostAsync()
{
return RedirectToPage("IndexPref");
}
}
相应的HTML代码:
@page
@model ConfirmModel
@{
ViewData["Title"] = "Confirm";
}
@if(!General.AddPreference)
{
<div>
<h4>Invalid go back</h4>
</div>
}
@if(!General.AddPreference)
{
<div>
<form enctype="multipart/form-data" id="orderForm" method="post">
<div class="Custom-Form col-md-12">
<input type="submit" value="Hinzufügen" class="Custom-Button" />
</div>
</form>
</div>
}
</div>
General是可用于任何类访问的常规类。看起来像这样:
public static bool GAddPreference = true;
public static bool AddPreference
{
get { return GAddPreference; }
set { GAddPreference = value; }
}
我是C#的新手,在某个地方我显然错了。我希望有人能帮助我。