今天,我试图将两种模型转移到Asp.net MVC5中的一个视图中。
我认为最好的方法就是创建新的ViewModel,其中包括我的两个ViewModel。我刚刚完成了此操作,但出现了奇怪的错误。您能看一下我的代码并告诉我,我在做什么错吗?
public class WeddingOfferViewModel
{
public WeddingViewModels Wedding { get; set; }
public List<OfferViewModel> Offer { get; set; }
}
还有控制器
public ActionResult BookDate()
{
var db = new OtherDbContext();
WeddingOfferViewModel WeddingOfferModel = new WeddingOfferViewModel
{
Offer = db.Offers.ToList()
};
return View(WeddingOfferModel);
}
//Wysyłanie danych odnośnie rezerwacji terminu
[HttpPost]
public ActionResult BookDate(WeddingOfferViewModel WeddingOfferViewModel, Wedding2OfferViewModel Wedding2Offer)
{
try
{
using (var db = new OtherDbContext())
{
//TODO: Dodać oferty do bazy danych, następnie przekazać je do Wedding2Offer, nastepnie zapisać do bazy danych!
var NewWedding = new WeddingOfferViewModel
{
Wedding = {UserId = User.Identity.GetUserId(),
Date = WeddingOfferViewModel.Wedding.Date,
NumberOfGuests = WeddingOfferViewModel.Wedding.NumberOfGuests,
LocationOfWedding = WeddingOfferViewModel.Wedding.LocationOfWedding}
};
var NewWedding2Offer = new Wedding2OfferViewModel { Offer_Id = 1, Wedding_Id = NewWedding.Wedding.Id };
db.Weddings.Add(NewWedding.Wedding);
db.Wedding2Offers.Add(NewWedding2Offer);
db.SaveChanges();
}
return View();
}
错误是:
对象引用未设置为对象的实例。