我在mvc工作我想保存详细信息.. 这里我有一个错误.. 控制器
public ActionResult Edit(FormCollection frm)
{
StaffDetails sdtl=new StaffDetails();
int UnvId = int.Parse(TempData["UnvID1"].ToString());
sdtl.UnvId = UnvId;
//sdtl.UnvId = int.Parse(TempData["UnvID"].ToString());
string SportsName = frm["SportsAffliation"];
var SpotsID = Db.SportsCodes.Where(s => s.SportsName == SportsName).FirstOrDefault();
sdtl.SportsID = SpotsID.SportsCodeID;
sdtl.Name = frm["name"];
sdtl.Address.Street = frm["street"];
sdtl.Address.City = frm["city"];
sdtl.Address.State = frm["state"];
sdtl.Address.PostalCode = frm["zip"];
sdtl.Address.Country = frm["country"];
sdtl.Email = frm["Email"];
sdtl.Phone = frm["Phone"];
sdtl.SportsAffliation = frm["SportsAffliation"];
Db.Entry(sdtl).State = System.Data.Entity.EntityState.Modified;
Db.SaveChanges();
//return RedirectToAction("Edit", new { id = cohid, tab = 0 });
return View();
}
域
public class StaffDetails
{
[Key]
public int StaffId { get; set; }
public int UnvId { get; set; }
public University University { get; set; }
public int SportsID { get; set; }
public SportsCode SportsCode { get; set; }
public int SportsGroupId { get; set; }
public SportsGroup SportsGroup { get; set; }
public int CoachingStaffId { get; set; }
public CoachingStaff CoachingStaff { get; set; }
public string Name { get; set; }
public string SportsAffliation { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string OrganizationalLeader { get; set; }
public Address Address { get; set; }
}
来自控制器的以下行错误.. 仅来自sdtl.address ...
的错误sdtl.Address.Street = frm["street"];
sdtl.Address.City = frm["city"];
sdtl.Address.State = frm["state"];
sdtl.Address.PostalCode = frm["zip"];
sdtl.Address.Country = frm["country"];
错误是{“对象引用未设置为对象的实例。”}
我认为这是一个合乎逻辑的问题,但我找不到因为我是mvc的新手。你可以解决这个问题
答案 0 :(得分:1)
您可以在构造函数中新建地址对象:
public StaffDetails()
{
Address = new Address();
}
或者在控制器的“编辑”操作中添加新地址。
public ActionResult Edit(FormCollection frm)
{
StaffDetails sdtl=new StaffDetails() { Address = new Address() };
// Rest of code
}
这种方式意味着每次使用StaffDetails时都必须新建Address对象。
答案 1 :(得分:0)
在您的班级中添加构造函数并初始化Address
proeperty:
public StaffDetails()
{
Address = new Address();
}
答案 2 :(得分:0)
我认为你应该为StaffDetails创建一个构造函数。在构造函数中,您应该初始化像地址这样的对象。我的意思是当你使用StaffDetails sdtl=new StaffDetails();
这一行时它会创建一个StaffDetails对象,但sdtl中的Address
对象仍为空。
答案 3 :(得分:0)
您应该从构造函数员工详细信息中的地址创建新实例: