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'。 –