我有其中有多个其他模型的模型。绑定多个模型asp,net mvc
public class mainmodel
{
public entity1();
public entity2();
}
发布视图后,我得到entity1实体null?运气好的话。我做错了? 我的问题是:Asp.net with MVC multiple model in one view (create, update) 如何获取模型中的类实体?
我有其中有多个其他模型的模型。绑定多个模型asp,net mvc
public class mainmodel
{
public entity1();
public entity2();
}
发布视图后,我得到entity1实体null?运气好的话。我做错了? 我的问题是:Asp.net with MVC multiple model in one view (create, update) 如何获取模型中的类实体?
控制器(HomeController中):
public ActionResult Index()
{
mainmodel model=new mainmodel();
return View(model);
}
[HttpPost]
public ActionResult Index(mainmodel model)
{
return View(model);
}
视图(首页/索引):
@model mainmodel
@using (Html.BeginForm("Index","Home",FormMethod.Post))
{
<input type="submit" value="Submit" />
}
是的,但我有IndexPageViewModel中的另一个类,不管用。 – 2013-03-13 07:25:29
您无法将多个模型与mvc中的一个视图绑定,因为它是1:1关系。如果你想这样做,你必须创建一个ViewModel,其中包含你想要在你的视图中绑定的模型。请参阅我的下一个答案中的代码。我希望它有帮助。 – 2013-03-13 08:02:44
视图模型(IndexViewModel):
public class IndexViewModel
{
public mainmodel model1 {get;set;}
public anotherclass model2 {get;set;}
}
控制器(HomeController中):
public ActionResult Index()
{
IndexViewModel model=new IndexViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
return View(model);
}
视图(首页/索引):
@model IndexViewModel
@using (Html.BeginForm("Index","Home",FormMethod.Post))
{
<input type="submit" value="Submit" />
}
现在你可以在HttpPost所有的值。
嗨,上面的作品,但正如我所说,我在部分视图中传递MainViewmodel.Entityclass。 @ Html.Partial(“_ Model1”,Model.MyModel1),它给出了错误。传入字典的模型项目类型为'MvcApplication1.Models.MainModel',但该字典需要一个'MvcApplication1.Models.Model1'类型的模型项目。 – 2013-03-13 09:17:56
要将哪个模型传递到您的部分视图中,您需要在页面顶部声明完全相同的模型(局部视图)。我认为您在部分视图顶部写入了“@model MvcApplication1.Models.MainModel”而不是“@model MvcApplication1.Models.Model1”,这是错误的。请在部分视图的顶部写上“@model MvcApplication1.Models.Model1”。 – 2013-03-13 10:02:21
请显示您的视图和控制器代码。 – 2013-03-13 06:54:33
在我看来,我正在渲染通过entity1和entity2的局部视图。所以我可以在发布后获取模型的值 – 2013-03-13 06:55:13
检查[This](http://stackoverflow.com/questions/15339272/how-to-pass-a-nested-model-value-in-html-partial/15339376#15339376 ) – 2013-03-13 06:58:05