Asp net MVC 5 and listbox with linq

本文关键字:listbox with linq and net MVC Asp | 更新日期: 2023-09-27 18:34:07

在阅读了几天关于如何用linq填充列表框之后,我完全不知道我必须做些什么才能完成这项工作。我知道我必须有一个视图模型或类似的东西,但由于我不能在同一视图中引用 2 个模型,我不知道该怎么办。

这是我的模型

public class ABC
{
    public int a { get; set; }
    public int b { get; set; }
    public int c { get; set; }
    public string d { get; set; }
    public string Type { get; set; }
    public int ID { get; set; }
    public class  ABCDBContext : DbContext
    {
        public DbSet<ABC> ABCs { get; set; }
    }
}
public class ABCModel
{
    public string type{ set; get; }
    public List<ABC> ABCs { set; get; }
}

我知道我缺少很多东西的控制器,但我不知道如何使用该 linq 查询填充列表,也不知道如何在不使用 beginform 的情况下从视图中调用此控制器(我将在此形式中拥有 1 个以上的列表框(

public ActionResult GetStuff()
    {
       var Types = from m in db.ABCs
                   select m.Type.Distinct();
        return View(Types); 
    }

然后在我看来,我需要有@model IEnumerable,所以我可以在该页面上显示表 abc 拥有的所有内容。

那么,我可以创建一个填充 lsitbox 的 viewModel(我需要用 abc 具有的参数填充至少 6,以便用户可以使用这些值搜索 abc,但我想如果我能理解如何做 1 我可以做 6(用我想要的,这允许我显示 abc 拥有的条目?

这是观点(我知道很多事情都有问题,但这只是举个例子(

@using (Html.BeginForm("getSelectedValues", "ABC", FormMethod.Get))
{
    Type:@Html.DropDownList() 
    a:@Html.DropDownList()
    b:@Html.DropDownList()
    //and so on
    <input type="submit" value="Filter" />
}

请原谅我对我错过的任何方面的无知,但我是 ASP Net MVC 5 的新手,如果有人可以指导我或向我发送有关我必须做的事情的指南,我将不胜感激。

Asp net MVC 5 and listbox with linq

我建议你创建一个名为MYPAGENAMEViewModel.cs的ViewModel,然后在该ViewModel中,你拥有view.cshtml文件所需的所有"模型"/数据。即如下所示:

public class MYPAGENAMEViewModel
{
    public List<Types> MyTypes { get; set; }
    public List<OtherTypes> MyOtherTypes { get; set; }
}

然后在你的行动中。

public ActionResult GetStuff()
{
   MYPAGENAMEViewModel myViewModel = new MYPAGENAMEViewModel();
   myViewModel.MyTypes = from m in db.ABCs
                       select m.Type.Distinct();
   myViewModel.MyOtherTypes = from m in db.CBAs
                              select m.Type.Distinct();
   return View(myViewModel); 
}

然后在视图的顶部:

@model MYPAGENAMEViewModel

然后稍后在视图中:

MyTypes<br />
@Html.DropDownListFor(model => model.MyTypes.TypeId, (SelectList)model.MyTypes.TypeName) 
MyOtherTypes<br />
@Html.DropDownListFor(model => model.MyOtherTypes.TypeId, (SelectList)model.MyOtherTypes.TypeName) 
我不

完全确定你在追求什么,但这可能是解决方案。

首先,您需要创建一个视图模型,例如:

public class MyViewModel
{
 List<ABC> abcs { get; set; } // Your database values that you're going to loop through
 List<WhateverALookupShouldBe> aDropDownValues { get; set; }
 List<WhateverBLookupShouldBe> bDropDownValues { get; set; }
 // etc
 }

在数据或控制器中填充这些值。

如果您要循环浏览列表并提交值,则需要编辑器,因此请在视图文件夹下创建一个名为"EditorTemplates"的文件夹。然后添加一个与您的模型同名的 cshtml 文件,例如 ABC。

在您的主视图中,您将拥有:

@model MyViewModel
@Html.EditorFor(model => model.abcs)

现在,在您的 ABC 编辑器模板中,您将为下拉列表编写类似以下内容:

@model ABC
@Html.DropDownListFor(model => model.a, new SelectList(Model.aDropDownValues, "DataValueFieldName", "DataTextFieldName"));

当您将其提交回时,您应该会将数据返回给您。