我正在尝试学习ASP.NET MVC。目前,我想呈现一个模型的创建页面,该页面引用了另一个模型,并让用户从下拉列表中选择另一个模型。更具体地说,这是Category
模型的代码
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
这是Food
模型的代码
public class Food
{
public int Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
}
考虑一下,我在内存中有一个名为categories
的类别列表,并且我想确保在将return View();
的{{1}}的{{1} }方法,他不仅获得要选择的名称,还获得HomeController
的下拉列表。还应考虑在不久的将来我想根据这些类生成数据库的表(实体框架代码优先方法),因此向这些类添加属性似乎不是一个好主意。
我该怎么办?
答案 0 :(得分:1)
您可以利用viewBag这样从控制器传递多个模型到视图
控制器
Public ActionResult Index()
{
viewbag.Childone=Childone();
viewbag.Childtwo=Childtwo()
return View(parentModel);
}
[HttpPost]
public ActionResult Index(ParentModel parentModel,Childone child_one ,Childtwo child_two)
{
//do something with models passed....
}
查看
@model parentModel
@{
Childone = viewbag.Childone as Childone;
Childtwo = viewbag.Childtwo as Childtwo;
}
//just use these models......like
//this is Main parent model
<p>@Model.propertyname</p>
//these are child
<p>@Childone.propertyname</p>
<p>@Childtwo.propertyname</p>
在模型提交按钮上单击
var parentModel = [
{ id: 1, color: 'yellow' },
];
var child_one = [
{ id: 1, color: 'yellow' },
];
var child_two = [
{ id: 1, color: 'yellow' },
];
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/Index',
data:JSON.stringify(parentModel:parentModel child_one:child_one,child_two:child_two),
success: function () {
},
failure: function (response) {
}
});