l當前正在使用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; }
}
當我米運行進而以創建一個標識和名稱的實體的實體的其餘部分返回null代碼如下。如果步驟結束,只有名稱返回一個值,其餘的將在ViewModel上返回一個空值。任何人都可以幫助我爲什麼viewModels是空值。先謝謝你。
創建視圖是什麼樣的? –
通過調用'ToUpperCase()'來爲每個屬性假設它們在視圖模型中具有值。當視圖模型中的字符串爲'null'時,這將導致'NullReferenceException'。 –