我正在尝试创建我的第一个ASP.NET MVC应用程序,但是两天后我无法解决我的问题。
我正在使用Entity Framework Code First方法。我想创建DropDownListFor,但始终存在此错误:
System.NullReferenceException System.Web.Mvc.WebViewPage.Model.get返回null。
我的模特:
public class Animals
{
public int AnimalsId { get; set; }
public int ClientsId { get; set; }
public string Name { get; set; }
public int TypesId { get; set; }
public float Age { get; set; }
public float Weight { get; set; }
public virtual Types Types { get; set; }
public IEnumerable<Clients> ClientsList { get; set; }
public virtual ICollection<BookVisit> AnimalsVisits { get; set; }
}
我的控制器:
public ActionResult Create([Bind(Include = "AnimalsId, ClientsId, Name, TypesId, Age, Weight")] Animals animals)
{
var person = new List<Clients>
{
new Clients { ClientsId = 50, Name = "Timo", Surname = "Werner", Email = "timo.werner@gmail.com", Phone = 123123123 }
};
var animalsView = new Animals
{
ClientsList = person.Select(x => new Clients
{
ClientsId = x.ClientsId
})
};
if (ModelState.IsValid)
{
db.Animals.Add(animals);
db.SaveChanges();
return RedirectToAction("List", "Animal");
}
return View(animalsView);
}
我的观点(仅限@model和下拉列表):
@model xyz.Models.Animals
@Html.DropDownListFor(model => model.ClientsId, new SelectList(Model.ClientsList, "ClientsId", "Name", "Surname", "Email", "Phone"))
你能看一下吗?
答案 0 :(得分:0)
从注释中看起来您没有将有效的视图模型对象传递给视图。您的视图代码期望传递给它的有效模型,并且辅助方法使用不同的属性。
public ActionResult Create()
{
var clients = new List<Clients>
{
new Clients { ClientsId = 50, Name = "Timo" },
new Clients { ClientsId = 51, Name = "Microsoft" }
};
var vm = new Animals
{
ClientsList = clients
};
return View(vm);
}
您当前调用DropDownListFor
的代码也是错误的。从集合创建SelectList
时,必须传递dataValue字段和dataText字段。
@model Animals
@Html.DropDownListFor(model => model.ClientsId,
new SelectList(Model.ClientsList, "ClientsId", "Name"))
答案 1 :(得分:0)
此错误也可能是由于尝试在剃刀视图中使用空模型引起的。在这种情况下,请在使用模型之前检查模型是否为空,如下所示:
@if (Model != null) {
<a onclick="get('@Url.Action("GetEmployee", "DemoController")', @Model.Id)" ></a>
}
希望这对您有帮助...