我刚刚开始学习Asp.net MVC5,我在下一行获得ArgumentNullException
。
@Html.DropDownListFor(m => m.Customer.MembershipTypeId, new SelectList(Model.MembershipTypes, "Id", "Name"), "", new { @class = "form-control" })
我正在关注一个教程并且我完全相同,所以我不确定为什么它会抛出这个错误。 我查看了模型和表格数据,并填充了它们。 如果需要任何其他信息来解决这个问题,请告诉我。
New.cshtml
@model Vidly6.VIewModel.NewCustomerViewModel
@{
ViewBag.Title = "New";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Customer</h2>
@using (Html.BeginForm("Create", "Customers"))
{
<div class="form-group">
@Html.LabelFor(m => m.Customer.Name)
@Html.TextBoxFor(m => m.Customer.Name, new {@class = "form-control"})
</div>
<div class="form-group">
@Html.LabelFor(m => m.Customer.BirthDate)
@Html.TextBoxFor(m => m.Customer.BirthDate, new {@class = "form-control"})
</div>
<div class="checkbox">
<label>
@Html.CheckBoxFor(m=>m.Customer.IsSubscribedToNewsletter) Subscribed to Newsletter?
</label>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Customer.MembershipTypeId)
@Html.DropDownListFor(m => m.Customer.MembershipTypeId, new SelectList(Model.MembershipTypes, "Id", "Name"), "", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Customer.MembershipTypeId)
</div>
}
NewCustomerViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Vidly6.Models;
namespace Vidly6.VIewModel
{
public class NewCustomerViewModel
{
public IEnumerable<MembershipTypes> MembershipTypes { get; set; }
public Customers Customer { get; set; }
}
}
CustomersController
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vidly6.Models;
using Vidly6.VIewModel;
namespace Vidly6.Controllers
{
public class CustomersController : Controller
{
private ApplicationDbContext _context;
public CustomersController()
{
_context = new ApplicationDbContext();
// GET: Customers
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
public ActionResult New()
{
var membershipTypes = _context.MembershipTypes.ToList();
var viewModel = new NewCustomerViewModel();
return View(viewModel);
}
public ViewResult CustomerGoesHere()
{
var customers = _context.Customers.Include(c => c.MembershipTypes).ToList();
return View(customers);
}
public ActionResult Details(int id)
{
var customer = _context.Customers.SingleOrDefault(c => c.Id == id);
if (customer == null)
return HttpNotFound();
return View(customer);
}
}
}
答案 0 :(得分:0)
public ActionResult New()
{
var membershipTypes = _context.MembershipTypes.ToList();
var viewModel = new NewCustomerViewModel();
return View(viewModel);
}
您实际上并未使用membershipTypes
。您需要在viewModel上设置属性,否则它将为null。