刚刚开始搞乱MVC,并试图通过查看此示例来实现此目的: http://forums.asp.net/t/1670552.aspx
我一直收到这个错误:
异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。
第9行:@using(Html.BeginForm(“Index”,“Home”,FormMethod.Post,new {id =“ID”})){
第10行:@ Html.DropDownListFor(m => m.id,新的SelectList(Model.list,“id”,“name”),“selectThis”)
第11行:}
以下是代码:
模型类(愚蠢的名字,我知道):
这些是在仅用于存储模型的控制台应用程序中。
namespace Model
{
public class Model
{
public int id { get; set; }
public string name { get; set; }
}
public class List
{
public int id { get; set; }
public List<Model> list = new List<Model>();
}
public class subModel
{
public int id { get; set; }
public int modId { get; set; }
public string name { get; set; }
}
public class subList
{
public List<subModel> list = new List<subModel>();
}
}
控制器:(用类中的方法填充subList.list和List.list,但现在决定以这种方式尝试,得到同样的错误)
namespace DropboxTest.Controllers
{
public class HomeController : Controller
{
//
// GET: /Model/
public ActionResult Index()
{
LoadModel();
return View();
}
[ValidateInput(false)]
[AcceptVerbs("POST")]
public ActionResult Index([Bind(Exclude = "id")]Model.Model model)
{
var modId = Request["id"];
LoadModel();
LoadSubCategory(Convert.ToInt32(modId));
return View();
}
public void LoadModel()
{
Model.List listM = new Model.List();
listM.id = 0;
Model.Model mod1 = new Model.Model();
mod1.id = 1;
mod1.name = "me";
Model.Model mod2 = new Model.Model();
mod2.id = 2;
mod2.name = "me";
listM.list.Add(mod1);
listM.list.Add(mod2);
ViewBag.Model = listM;
}
public void LoadSubCategory(int id)
{
Model.subList subList = new Model.subList();
Model.subModel sub1 = new Model.subModel();
Model.subModel sub2 = new Model.subModel();
sub1.id = 1;
sub1.name = "notme";
sub1.modId = 1;
sub2.id = 1;
sub2.name = "notme";
sub2.modId = 1;
subList.list.Add(sub1);
subList.list.Add(sub2);
List<Model.subModel> sel = new List<Model.subModel>();
foreach (var item in subList.list)
{
if (item.modId == id)
{
sel.Add(item);
}
}
ViewBag.SubModel = sel;
}
}
}
查看:(我不知道subModel下拉列表是否正常工作,因为我还没有达到那个部分,但是没有。)
@model Model.List
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
@using (Html.BeginForm("Index","Home",FormMethod.Post, new{id = "ID"})){
@Html.DropDownListFor(m=>m.id, new SelectList(Model.list, "id","name"),"selectThis")
}
@if (ViewBag.SubModel != null)
{
@Html.DropDownList("SubModel",ViewBag.SubModel as SelectList, "select one")
}
这可能是非常愚蠢的事情,但我已经被困了几个小时尝试不同的事情。
PS:这只是一个测试应用。在我看到它是如何完成之后,我将使用和SQL DB一起使用,使用ConsoleApplications中的模型从数据库中检索和存储数据并将其显示在视图中,因此对此的任何建议也将受到赞赏。
非常感谢所有读到这里并度过美好时光的人们。
答案 0 :(得分:0)
您永远不会将模型传递给控制器中的视图,只需将其存储在ViewBag.Model
。
尝试以下内容:
[ValidateInput(false)]
[AcceptVerbs("POST")]
public ActionResult Index([Bind(Exclude = "id")]Model.Model model)
{
var modId = Request["id"];
//get model
var model = LoadModel();
//pass it to the view
return View(model);
}