C# 当模型引用另一个模型时,如何渲染“创建视图”?

C# 当模型引用另一个模型时,如何渲染“创建视图”?,c#,asp.net,.net,asp.net-mvc,entity-framework,C#,Asp.net,.net,Asp.net Mvc,Entity Framework,我正在努力学习ASP.NETMVC。目前,我想呈现一个模型的创建页面,该页面引用了另一个模型,并让用户从下拉列表中选择另一个模型。更具体地说,这里是类别模型的代码 public class Category { public int Id { get; set; } public string Name { get; set; } } public class Food { public int Id { get; set; } public string Na

我正在努力学习ASP.NETMVC。目前,我想呈现一个模型的创建页面,该页面引用了另一个模型,并让用户从下拉列表中选择另一个模型。更具体地说,这里是
类别
模型的代码

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class Food
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category Category { get; set; }
}
这是
食品
模型的代码

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class Food
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category Category { get; set; }
}
假设我有一个名为
categories
的内存中类别列表,我想确保当我使用
returnview()向用户发送create视图时
HomeController
Create
方法中,他不仅获得了要选择的名称,还获得了
类别的下拉列表。此外,我认为,在不久的将来,我想根据这些类生成数据库表(实体框架代码第一方法),因此向类中添加属性似乎不是一个好主意。

我该怎么做?

您可以使用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>

你试过什么,什么不起作用?建议您参考示例中的代码,了解如何生成dropdownlist。没有一种方法可以不使用javascript,只将这两个类发送到服务器而不使用javascript。