[英]Object reference not set to an instance of an object
我目前正在研究Mvc 4應用程序。 我的創建控制器如下。
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult Create(OfficeCreateModels model)
{
bool success = false;
string message = "";
try
{
if (model.Name.IsNullOrWhitespace()) throw new Exception("Unable to create this Office Name. The Type cannot be blank or spaces.");
var company = models.Companies.FirstOrDefault(x => x.Id == model.CompanyId);
var officeExist = models.Offices.Any(x => x.Name.ToLower() == model.Name.ToLower() && x.CompanyId == model.CompanyId);
if (officeExist)
throw new Exception(string.Format("Company '{0}' already has an Office this named '{1}'" .FormatWith(company.Name.ToUpperCase(), model.Name.ToUpperCase())));
Office office = new Office
{
Name = model.Name.ToUpperCase(),
Address1 = model.Address1.ToUpperCase(),
Address2 = model.Address2.ToUpperCase(),
Address3 = model.Address3.ToUpperCase(),
Telephone = model.Telephone.ToUpperCase(),
Fax = model.Fax.ToUpperCase(),
Email = model.Email.ToUpperCase(),
AccountType = model.AccountType.ToUpperCase()
};
models.Offices.Add(office);
models.SaveChanges();
success = true;
return RedirectToAction("Index");
}
catch (Exception ex)
{
message = ex.Message;
}
return View(model);
}
我的ViewModels和DataModels分別如下
public class OfficeCreateModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string Telephone { get; set; }
public string Fax { get; set; }
public string Email { get; set; }
public Guid CompanyId { get; set; }
public bool IsDeleted { get; set; }
}
//DataModels
public class Office
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(100)]
public string Address1 { get; set; }
[MaxLength(100)]
public string Address2 { get; set; }
[MaxLength(100)]
public string Address3 { get; set; }
[MaxLength(20)]
public string Telephone { get; set; }
[MaxLength(20)]
public string Fax { get; set; }
[MaxLength(255)]
public string Email { get; set; }
public Guid CompanyId { get; set; }
public virtual Company Company { get; set; }
public virtual List<Agent> Agents { get; set; }
}
當我運行代碼時,它將繼續創建Id和Name實體,其余實體返回null。 如果l結束,則僅Name返回一個值,其余返回ViewModels上的null。 誰能幫助我為什么viewModels為null。 先感謝您。
Create
方法的簽名中的OfficeCreateModels
是什么? 您只發布了OfficeCreateModel
類。 models
是什么? 在方法主體中,僅使用變量model
(並在方法簽名中聲明)。 我將看看您使用的變量。 由於未初始化這些變量,因此您似乎具有NullReference異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.