#c# #asp.net-mvc #model-view-controller #razor-pages
#c# #asp.net-mvc #model-view-controller #razor-страницы
Вопрос:
У меня есть эта страница razor, которая в конечном итоге будет принимать информацию о кредитной карте. У меня есть модель, связанная со страницей razor. Выдается ошибка
Исключение NullReferenceException: ссылка на объект не установлена для экземпляра объекта. AspNetCore.Views_PaymentPage_CreditCardEntry.ExecuteAsync() в CreditCardEntry.cshtml
@page
@model InTheCloud.Views.PaymentPage.CreditCardEntryModel;
**@{ ViewData["Title"] = "Home Page";}**
Как вы можете видеть, ViewData выделен как проблема.
Я понимаю, что, возможно, я неправильно смешиваю технологию MVC и Razor Pages, но не уверен, как это исправить?
Вот моя модель:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace InTheCloud.Views.PaymentPage
{
[AllowAnonymous]
public class CreditCardEntryModel : PageModel
{
public async Task OnGetAsync()
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
}
public CreditCardEntryModel()
{
Information = new Info()
{
FirstName= "",
LastName = "",
AddressLine1 = "",
AddressLine2 = "",
City = "",
State = "",
Zip = "",
CCNumber = "",
CCExpiDate = "",
CVCCode = ""
};
}
[BindProperty]
public Info Information { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class Info
{
[Required]
public String FirstName { get; set; }
[Required]
public String LastName { get; set; }
public String AddressLine1 { get; set; }
public String AddressLine2 { get; set; }
public String City { get; set; }
public String State { get; set; }
public String Zip { get; set; }
public String CCNumber { get; set; }
public String CCExpiDate { get; set; }
public String CVCCode { get; set; }
}
public IEnumerable<SelectListItem> StatesList
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text = "Alabama", Value = "Alabama"},
new SelectListItem { Text = "Alaska", Value = "Alaska"},
new SelectListItem { Text = "Arizona", Value = "Arkansas"},
new SelectListItem { Text = "California", Value = "California"},
new SelectListItem { Text = "Colorado", Value = "Colorado"},
new SelectListItem { Text = "Conneticut", Value = "Conneticut"},
new SelectListItem { Text = "Delaware", Value = "Delaware"},
new SelectListItem { Text = "District of Columbia", Value = "District of Columbia"},
new SelectListItem { Text = "Florida", Value = "Florida"},
new SelectListItem { Text = "Georgia", Value = "Georgia"},
new SelectListItem { Text = "Hawaii", Value = "Hawaii"},
new SelectListItem { Text = "Idaho", Value = "Idaho"},
new SelectListItem { Text = "Illinois", Value = "Illinois"},
new SelectListItem { Text = "Indiana", Value = "Indiana"},
new SelectListItem { Text = "Iowa", Value = "Iowa"},
new SelectListItem { Text = "Kansas", Value = "Kansas"},
new SelectListItem { Text = "Kentucky", Value = "Kentucky"},
new SelectListItem { Text = "Louisiana", Value = "Louisiana"},
new SelectListItem { Text = "Maine", Value = "Maine"},
new SelectListItem { Text = "Maryland", Value = "Maryland"},
new SelectListItem { Text = "Massachusetts", Value = "Massachusetts"},
new SelectListItem { Text = "Michigan", Value = "Michigan"},
new SelectListItem { Text = "Minnesota", Value = "Minnesota"},
new SelectListItem { Text = "Missisippi", Value = "Arkansas"},
new SelectListItem { Text = "Missouri", Value = "Missouri"},
new SelectListItem { Text = "Montana", Value = "Montana"},
new SelectListItem { Text = "Nebraska", Value = "Nebraska"},
new SelectListItem { Text = "Nevada", Value = "Nevada"},
new SelectListItem { Text = "New Hampshire", Value = "New Jersey"},
new SelectListItem { Text = "New Mexico", Value = "New Mexico"},
new SelectListItem { Text = "New York", Value = "New York"},
new SelectListItem { Text = "North Carolina", Value = "North Carolina"},
new SelectListItem { Text = "North Dakota", Value = "North Dakota"},
new SelectListItem { Text = "Ohio", Value = "Ohio"},
new SelectListItem { Text = "Oklahoma", Value = "Oklahoma"},
new SelectListItem { Text = "Oregon", Value = "Oregon"},
new SelectListItem { Text = "Pennsylvania", Value = "Pennsylvania"},
new SelectListItem { Text = "Rhode Island", Value = "Rhode Island"},
new SelectListItem { Text = "South Carolina", Value = "South Carolina"},
new SelectListItem { Text = "South Dakota", Value = "South Dakota"},
new SelectListItem { Text = "Tennessee", Value = "Tennessee"},
new SelectListItem { Text = "Texas", Value = "Texas"},
new SelectListItem { Text = "Utah", Value = "Utah"},
new SelectListItem { Text = "Vermont", Value = "Vermont"},
new SelectListItem { Text = "Virginia", Value = "Virginia"},
new SelectListItem { Text = "Washington", Value = "Washington"},
new SelectListItem { Text = "West Virginia", Value = "West Virginia"},
new SelectListItem { Text = "Wisconsin", Value = "Wisconsin"},
new SelectListItem { Text = "Wyoming", Value = "Wyoming"}
};
}
}
public async Task<IActionResult> AsyncOnPost(Info CreditCardEntryInfo)
{
if (ModelState.IsValid)
{
ModelState.AddModelError("Information.FirstName", "Invalid login");
Console.Out.Write("Model is fine!");
return Page();
}
return Page();
}
}
}
и вот моя страница Razor:
@page
@model InTheCloud.Views.PaymentPage.CreditCardEntryModel;
@{ ViewData["Title"] = "Home Page";}
<head>
<link rel="stylesheet" type="text/css" href="~/css/indexstylesheet.css">
</head>
<div class="row">
<div class="col" style="border-right:solid; border-right-width:thin; border-right-color:lightgray; width: 20%;">
<div class="salesitems">
<span style="font-family:cursive; font-size:xx-large;">$0.99</span> <span style="font-family:cursive; font-size:x-large;">/mo.</span><br />
<div style="background-color:#fecc06;" width="100%"><span style="font-family:cursive ;font-size:xx-large; color:white;">50 GB</span></div>
<div style="text-align: left !important; padding-left:5pt; padding-right:5pt; min-height:133pt;">
<span style="text-align:left; font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif">
-Optional File Encryption<br />
-Secure File Transfers<br />
-Apps for Access from any Device<br />
-Simplest to Use<br />
-Redundancy for Data Recovery
</span>
</div>
<div style="position:absolute; height:40pt; padding-top:4pt; width:100%; background-color:lightgray; font-family:cursive; font-size:xx-large; text-align:center; color:black; border-bottom-left-radius:5pt; border-bottom-right-radius:5pt;">Choose</div>
</div>
</div>
<div class="col" style="margin: 10pt;">
<form method="post" id="Information">
<div class="form-group row">
<label asp-for="Information.FirstName" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Information.FirstName" class="form-control" />
</div>
<div class="col-sm-10">
<span asp-validation-for="Information.FirstName" class="text-danger">Hello</span>
</div>
</div>
<div class="form-group row">
<label asp-for="Information.LastName" class="col-sm-2 col-form-label">Last Name</label>
<div class="col-sm-10">
<input asp-for="Information.LastName" class="form-control" placeholder="Last" />
</div>
</div>
<div class="form-group row">
<label asp-for="Information.AddressLine1" class="col-sm-2 col-form-label">Street</label>
<div class="col-sm-10">
<input asp-for="Information.AddressLine1" class="form-control" placeholder="Street and Number" /><br />
<input asp-for="Information.AddressLine2" class="form-control" placeholder="" />
</div>
</div>
<div class="form-group row">
<label asp-for="Information.City" class="col-sm-2 col-form-label">City</label>
<div class="col-sm-10">
<input asp-for="Information.City" class="form-control" placeholder="City" />
</div>
</div>
<div class="form-group row">
<label asp-for="Information.State" class="col-sm-2 col-form-label">State</label>
<div class="col-sm-10">
@Html.DropDownListFor(model => model.Information.State, Model.StatesList, new { @class = "form-control" });
</div>
</div>
<div class="form-group row">
<label asp-for="Information.CCNumber" class="col-sm-2 col-form-label">Credit Card Number</label>
<div class="col-sm-10">
<input asp-for="Information.CCNumber" class="form-control" placeholder="Card Number" />
</div>
</div>
<div class="form-group row">
<label asp-for="Information.CCExpiDate" class="col-sm-2 col-form-label">Expiration Date</label>
<div class="col-sm-10">
<input asp-for="Information.CCExpiDate" class="form-control" placeholder="mm/yy" />
</div>
</div>
<div class="form-group row">
<label asp-for="Information.CVCCode" class="col-sm-2 col-form-label">CVC</label>
<div class="col-sm-10">
<input asp-for="Information.CVCCode" class="form-control" placeholder="CVC" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<button type="submit" class="btn primary-btn">submit</button>
</div>
</div>
</form>
</div>
</div>
Пожалуйста, дайте мне знать, что я делаю не так.
Комментарии:
1. Вы не возвращаете Страницу в OnGetAsync
Ответ №1:
Я понял это! Я думаю, что это был мой подход, который был немного странным. Я переработал страницу в новую область, включив @section Scripts { } для выполнения проверки и сохранил ее строго на страницах Razor, и все работает нормально. Страница(), а не Просмотр(). Оказывается, для проверки на стороне клиента требуется файл ненавязчивой проверки jQuery, который можно найти в _ValidationScriptPartial. Спасибо!