如何在视图中加载多个控件

时间:2011-06-02 09:07:16

标签: asp.net-mvc-3 view controller razor

我仍然无法在MVC 3上开始准备这样的表格。

我是初学者,到目前为止我所学到的只是将数据从控制器绑定到强类型视图。但据我所知,我们只能从返回陈述中返回一个变量

public ActionResult(int id) {    //做一些逻辑    return View(角色); }

现在上面的代码将角色列表返回给视图。但是我如何传递其他细节,如许可证状态,组织......等等*

另一个复杂的例子:

假设我的表单需要显示详细信息,如国家[下拉],状态[下拉],部门[组合框列表],组织[单选按钮列表],所有员工列表[表格/网格]

如何使用单个RETURN显示所有控件值?

注意:*我假设所有的detials,如角色,许可证状态,组织等我从数据库中获取。

我希望我的解释清楚,如果我需要进一步解释,请告诉我。

此外,我很抱歉这个愚蠢的问题,这是因为我处于MVC的第一个学习阶段

enter image description here

1 个答案:

答案 0 :(得分:1)

你会写一个视图模型:

public class MyViewModel
{
    public SomeModel1 Section1 { get; set; }
    public SomeModel2 Section2 { get; set; }
    public SomeModel3 Section3 { get; set; }
}

在控制器操作中,您将此视图模型返回到视图:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Section1 = ...,
            Section2 = ...,
            Section3 = ...,
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        ... process the model when the form is submitted
    }
}

并在视图中:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Section1)
    @Html.EditorFor(x => x.Section2)
    @Html.EditorFor(x => x.Section3)
    ...
}

当然,每个部分都会有强类型的编辑器模板:

  • 〜/查看/共享/ EditorTemplates / SomeModel1.cshtml
  • 〜/查看/共享/ EditorTemplates / SomeModel2.cshtml
  • 〜/查看/共享/ EditorTemplates / SomeModel3.cshtml
  • ...

代表每个部分的部分内容