我設法註冊一個applicationuser,現在我想提出一個HTTP GET請求,它在View中顯示當前登錄用戶的賬戶詳細信息。爲什麼我的嵌套CustomerViewModel爲空?
但是,當我運行應用程序並轉到「MyPages」視圖時,出現異常,表明嵌套的CustomerViewModel爲空。我完全不知道爲什麼,但出於某種原因。
這是HomeController.cs的ActionResult的
public ActionResult MyPages()
{
string userId = User.Identity.GetUserId();
var currentUser = _userRepository.GetById(userId);
var customer = _customerRepository.GetById(currentUser.Customer.Id);
var userViewModel = new UserViewModel();
userViewModel.Id = currentUser.Id;
userViewModel.UserName = currentUser.UserName;
//This is where the exception occurs. Apperantly CustomerViewModel is null
userViewModel.CustomerViewModel.Id = customer.Id;
userViewModel.CustomerViewModel.FirstName = customer.FirstName;
userViewModel.CustomerViewModel.LastName = customer.LastName;
userViewModel.CustomerViewModel.Email = customer.Email;
return View(userViewModel);
}
這是UserViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using Microsoft.AspNet.Identity.EntityFramework;
namespace GUI.Models
{
public class UserViewModel
{
public virtual string Id { get; set; }
public virtual string UserName { get; set; }
public virtual string PasswordHash { get; set; }
public virtual string SecurityStamp { get; set; }
public virtual ICollection<IdentityUserRole> Roles { get; set; }
public virtual ICollection<IdentityUserClaim> Claims { get; set; }
public virtual ICollection<IdentityUserLogin> Logins { get; set; }
public CustomerViewModel CustomerViewModel { get; set; }
}
}
這是CustomerViewModel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using ClassLibrary.Entities;
namespace GUI.Models
{
public class CustomerViewModel
{
public Guid Id { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Email Adress")]
[Required(ErrorMessage = "Email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
public List<InvoiceViewModel> InvoiceViewModels { get; set; }
public List<AddressViewModel> AdressViewModels { get; set; }
public AddressViewModel AdressViewModel { get; set; }
public virtual ICollection<Invoice> Invoice { get; set; }
public virtual ICollection<Adress> Adress { get; set; }
}
}
似乎是什麼問題這裏?
CustomerViewModel是更換您的UserViewModel Model類null,你必須聲明像 ** var userViewModel = new UserViewModel(); ** –