我正在尝试填充一个下拉列表。最初,一切都按照我的预期运行。但是,当我离开原始视图导航并返回时,出现此错误:
System.NullReferenceException:'对象引用未设置为 对象的实例。” System.Web.Mvc.WebViewPage.Model.get 返回null。
我尝试添加一个if语句来说明一个空模型,但这没有用。 (我现在把它拿出来了)
谢谢。
型号:
public class IndexDates
{
public List<PeriodEndDates> ListForDropDown { get; set; }
}
控制器:
public ActionResult Index(IndexDates datesParam)
{
using (PayrollEntities2 db = new PayrollEntities2())
{
DateTime todaysDate = DateTime.Now;
var model = new IndexDates()
{
ListForDropDown = db.PeriodEndDates2
.Where(x => x.periodEndDate <= todaysDate)
.OrderByDescending(x => x.periodEndDate )
.ToList()
};
return View(model);
}
}
查看:
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<div class="schedule-bottom">
<p>Period End Date: @Html.DropDownListFor(model => model.ListForDropDown, new SelectList(Model.ListForDropDown, "periodEndDate", "periodEndDate"), "Select...", new { onChange = "selectedtext(this)" })</p>
</div>
}
PayrollEntities2:
public partial class PayrollEntities2 : DbContext
{
public PayrollEntities2()
: base("name=PayrollEntities2")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<PeriodEndDates2> PeriodEndDates2 { get; set; }
}
家庭控制器重定向:
[HttpPost]
public ActionResult Authorize(UsersAndDates userModel)
{
using (MasterTable db = new MasterTable())
{
var userDetails = db.PaybillUsers.Where(x => x.userName == userModel.userName && x.password == userModel.password).FirstOrDefault();
var datesToDisplay = db.PeriodEndDates2
.Where(x => x.ffsPayDate > DateTime.Now)
.Select(x => new PayDates
{
PayDate = x.ffsPayDate,
PeriodEndDate = x.periodEndDate
})
.FirstOrDefault();
if (userDetails == null)
{
return View("Login", userModel);
}
else
{
Session["userID"] = userDetails.userName.ToString();
Session["payDate"] = datesToDisplay.PayDate.ToString();
Session["endDate"] = datesToDisplay.PeriodEndDate.ToString();
return RedirectToAction("Index", "Dashboard");
}
}
}
答案 0 :(得分:0)
我认为是因为您使用了using (PayrollEntities2 db = new PayrollEntities2())
而不是仅仅声明它。