在 ASP.NET MVC 5 视图中访问泛型列表

Access Generics List in ASP.NET MVC 5 View

我正在开始使用 MVC,我有以下模型

public class FormControls
{

    //Properties of the FormControls object
    public string formCName { get; set; }
    public string formCType { get; set; }
    public string formCCss { get; set; }
    public string formCEnabled { get; set; }
    public string formCDefaultVal { get; set; }

}

我还创建了以下控件,我正在使用 linq to select 记录查询数据库。然后必须将每条记录添加到列表中。

    public ActionResult Index()
    {

        var DataContext = new EditProfileFormFieldsDataContext();
        var controls = from c in DataContext.Controls
                       select c;

        List<FormControls> Fields = new List<FormControls>();

        foreach(var fc in controls)
        {


            //Create Object for Generic List
            FormControls epc = new FormControls();
            epc.formCName = fc.Control_Name;
            epc.formCType = fc.Control_Type;
            epc.formCCss = fc.Control_CSS;
            epc.formCEnabled = fc.Control_Enabled;
            epc.formCDefaultVal = fc.Control_DefaultVal;

            //Add Object to FormControls Generic List
            Fields.Add(epc);
        }



        return View("EditProfile");
    }

我的问题是如何在视图中使用 RAZOR 访问列表?我正在尝试遍历我在视图中创建的列表。我是 MVC 的新手,我想我想太多了 :) 谢谢!

您可以将您的视图模型设为列表。把这个放在你的视图的顶部:

@model List<FormControls>

更改 Index() 方法的 return:

return View("EditProfile", Fields);

然后您可以使用@Model 从视图中访问它。例如,要遍历它:

@foreach (var field in Model)
{
    <p>@field.formCName</p>
}

顺便说一句,还有更直接的方法来实现控制器。

public ActionResult Index()
{
    var DataContext = new EditProfileFormFieldsDataContext();
    return View("EditProfile", DataContext.Controls.ToList());
}

或者如果您将视图重命名为 "index.cshtml",您可以这样做:

public ActionResult Index()
{
    var DataContext = new EditProfileFormFieldsDataContext();
    return View(DataContext.Controls.ToList());
}

假设你还没有index.cshtml,右击"View("和select"Add View",在弹出的向导中,select "list view" 和 FormControls,将有一个自动生成的视图,其中定义了 @model 并且做得很好 table 演示如何使用它。