对象引用未设置到对象 ViewData["Title"] = "Index" 的实例;
Object reference not set to an instance of an object ViewData["Title"] = "Index";
所以我正在尝试使用模式在我的索引页面中创建一个注册剃刀页面。我导入模态的大部分表单代码来自现有的外部注册页面。但是,当我启动 mvc 应用程序时,我收到 Object reference not set to an instance of an object
错误。任何帮助,将不胜感激。谢谢!
控制台:
System.NullReferenceException: Object reference not set to an instance of an object.at AspNetCore.Views_Home_Index.ExecuteAsync() in C:\Users\SalvadorSolis\source\repos\AWSCognitoMVC\AWSCognitoMVC\Views\Home\Index.cshtml:line 4
HTML:
@page
@model AWSCognitoMVC.Views.Home.IndexModel
@{
ViewData["Title"] = "Index";//line 4
}
<h2>@ViewData["Title"]</h2>
型号:
namespace AWSCognitoMVC.Views.Home
{
[AllowAnonymous]
public class IndexModel : PageModel
{
private readonly SignInManager<CognitoUser> _signInManager;
private readonly CognitoUserManager<CognitoUser> _userManager;
private readonly ILogger<IndexModel> _logger;
private readonly CognitoUserPool _pool;
public IndexModel(
UserManager<CognitoUser> userManager,
SignInManager<CognitoUser> signInManager,
ILogger<IndexModel> logger,
CognitoUserPool pool)
{
_userManager = userManager as CognitoUserManager<CognitoUser>;
_signInManager = signInManager;
_logger = logger;
_pool = pool;
}
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(15, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 10)]
[Phone]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[Required]
[Display(Name = "User Name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public void OnGet()
{
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
//Added because users don't usually add in a + in their phone number
if (!(Input.PhoneNumber.First() == '+'))
{
Input.PhoneNumber = "+" + Input.PhoneNumber;
}
//Added because users don't usually add in a + in their phone number
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var user = _pool.GetUser(Input.UserName);
user.Attributes.Add(CognitoAttributesConstants.Email, Input.Email);
user.Attributes.Add(CognitoAttributesConstants.PreferredUsername, Input.UserName);
user.Attributes.Add(CognitoAttributesConstants.PhoneNumber, Input.PhoneNumber);
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToPage("./ConfirmAccount");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return Page();
}
}
}
家庭控制器:
namespace AWSCognitoMVC.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
注意:原始寄存器模型没有定义 "Title" 并且不知何故工作正常。
ViewData 是一个容器,用于将数据从 PageModel 传递到内容页面。
所以我想以这种方式在 PageModel 端设置数据是有意义的:
public class IndexModel : PageModel
{
[ViewData]
public string Title{ get; set; }
public void OnGet()
{
Title = "Index";
}
// ...
}
然后就这样得到它:
<h2>@ViewData["Title"]</h2>
您正在尝试将控制器和视图方法与剃刀页面混合使用。只是不要这样做。如果您想使用 razor pages,请在项目的根目录中创建 Pages
文件夹,并在其中创建您的 razor 页面。如果您想通过 /home/index
url 显示剃刀页面的视图,请在 Pages
文件夹中创建 Home
文件夹并在其中添加您的 IndexModel
。
Pages\Home\Index.cshtml
阅读更多in the docs。
所以我正在尝试使用模式在我的索引页面中创建一个注册剃刀页面。我导入模态的大部分表单代码来自现有的外部注册页面。但是,当我启动 mvc 应用程序时,我收到 Object reference not set to an instance of an object
错误。任何帮助,将不胜感激。谢谢!
控制台:
System.NullReferenceException: Object reference not set to an instance of an object.at AspNetCore.Views_Home_Index.ExecuteAsync() in C:\Users\SalvadorSolis\source\repos\AWSCognitoMVC\AWSCognitoMVC\Views\Home\Index.cshtml:line 4
HTML:
@page
@model AWSCognitoMVC.Views.Home.IndexModel
@{
ViewData["Title"] = "Index";//line 4
}
<h2>@ViewData["Title"]</h2>
型号:
namespace AWSCognitoMVC.Views.Home
{
[AllowAnonymous]
public class IndexModel : PageModel
{
private readonly SignInManager<CognitoUser> _signInManager;
private readonly CognitoUserManager<CognitoUser> _userManager;
private readonly ILogger<IndexModel> _logger;
private readonly CognitoUserPool _pool;
public IndexModel(
UserManager<CognitoUser> userManager,
SignInManager<CognitoUser> signInManager,
ILogger<IndexModel> logger,
CognitoUserPool pool)
{
_userManager = userManager as CognitoUserManager<CognitoUser>;
_signInManager = signInManager;
_logger = logger;
_pool = pool;
}
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(15, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 10)]
[Phone]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[Required]
[Display(Name = "User Name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public void OnGet()
{
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
//Added because users don't usually add in a + in their phone number
if (!(Input.PhoneNumber.First() == '+'))
{
Input.PhoneNumber = "+" + Input.PhoneNumber;
}
//Added because users don't usually add in a + in their phone number
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var user = _pool.GetUser(Input.UserName);
user.Attributes.Add(CognitoAttributesConstants.Email, Input.Email);
user.Attributes.Add(CognitoAttributesConstants.PreferredUsername, Input.UserName);
user.Attributes.Add(CognitoAttributesConstants.PhoneNumber, Input.PhoneNumber);
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToPage("./ConfirmAccount");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return Page();
}
}
}
家庭控制器:
namespace AWSCognitoMVC.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
注意:原始寄存器模型没有定义 "Title" 并且不知何故工作正常。
ViewData 是一个容器,用于将数据从 PageModel 传递到内容页面。
所以我想以这种方式在 PageModel 端设置数据是有意义的:
public class IndexModel : PageModel
{
[ViewData]
public string Title{ get; set; }
public void OnGet()
{
Title = "Index";
}
// ...
}
然后就这样得到它:
<h2>@ViewData["Title"]</h2>
您正在尝试将控制器和视图方法与剃刀页面混合使用。只是不要这样做。如果您想使用 razor pages,请在项目的根目录中创建 Pages
文件夹,并在其中创建您的 razor 页面。如果您想通过 /home/index
url 显示剃刀页面的视图,请在 Pages
文件夹中创建 Home
文件夹并在其中添加您的 IndexModel
。
Pages\Home\Index.cshtml
阅读更多in the docs。