我正在尝试学习MVC ASP.NET。目前,我想渲染一个模型的创建页面,该页面引用了另一个模型,并让用户从下拉列表中选择另一个模型。更具体地说,这是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
的类别列表,我想确保当我在HomeController
的Create
方法中使用return View();
向用户发送创建视图时,他不仅会获得要选择的名称,还会获得categories
的下拉列表。还要考虑到在不久的将来,我想根据这些类(实体框架代码优先方法(生成数据库表,因此向类添加属性似乎不是一个好主意。 我该怎么做?
您可以使用 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) {
}
});