[英]Update record and add new record in another model using updated values in asp.net mvc
我正在尝试使用asp.net mvc 4
和EF6
开发一个网站,我想在其中更新记录,并使用更新记录中的值将新记录添加到另一个模型中。 到目前为止,我可以更新现有记录,但是当系统尝试将新记录添加到另一个模型时,控制器中出现错误。 错误是
你调用的对象是空的。
这是我的代码,
调节器
[HttpPost]
public ActionResult RentController(FlatModel flatId)
{
if (Session["AdminNAME"] != null)
{
if (ModelState.IsValid)
{
var dbPost = rentdb.FlatInfoes.Where(p => p.flatno == flatId.Flats.flatno).FirstOrDefault();
if (dbPost == null)
{
return RedirectToAction("RentController");
}
dbPost.flat_owner_name = flatId.Flats.flat_owner_name;
dbPost.flat_owner_phone = flatId.Flats.flat_owner_phone;
var addRentSchedule = flatId.BillCheck;
addRentSchedule.fullname = flatId.Flats.flat_owner_name; //error showing in this line.
addRentSchedule.isRented = "N";
addRentSchedule.due = 10000;
DateTime today = DateTime.Now;
DateTime newDay = today.AddDays(30);
addRentSchedule.submitTime = newDay;
rentdb.BillPayChecks.Add(addRentSchedule);
rentdb.SaveChanges();
TempData["flat_assign_success"] = "Information Updated Successfully!";
return RedirectToAction("RentController");
}
else
{
TempData["flat_assign_fail"] = "Error! Information update failed!";
return RedirectToAction("RentController");
}
}
else
{
return RedirectToAction("AdminLogin");
}
}
模型
public class FlatModel
{
public FlatInfo Flats { get; set; }
public BillPayCheck BillCheck { get; set; }
}
我在代码中做错了吗? 更新模型时如何从更新后的值中添加记录? 急需此帮助。 TNX。
这只是“对我的代码进行故障排除”类型的问题,因此很难获得准确的答案。 但是,看这条线
var addRentSchedule = flatId.BillCheck;
让我认为您正在获取Null参考。 您正在这一行之后的那一行看到错误,因为您试图在一个空对象上设置属性。 如果租期表实际上是一个NEW数据库记录,则很可能需要创建一个新对象。 因此,您的代码可能看起来应该像这样:
var addRentSchedule = new BillCheck();
//you need to tie this to the parent record using the parent record
//primary key and setting the BillCheck Foreign key appropriately
//since I dont know your db schema, I am guessing on this line.
addRentSchedule.flatId = flatId.Id;
addRentSchedule.fullname = flatId.Flats.flat_owner_name;
addRentSchedule.isRented = "N";
addRentSchedule.due = 10000;
//no point in creating variables when you can do it all in one line here.
addRentSchedule.submitTime = DateTime.Now.AddDays(30);
rentdb.BillPayChecks.Add(addRentSchedule);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.