MVC创建列表并填写自动

时间:2015-08-15 12:03:47

标签: c# asp.net-mvc

如何创建一个空列表并使用多个控件将所有项目放入列表中 这是我想要列在列表中的项目;

process = Subprocess([command], 
    stdout=Subprocess.STREAM, stderr=Subprocess.STREAM,
    shell=True)
out, err = yield [process.stdout.read_until_close(),
    process.stderr.read_until_close()]

我已经尝试过这样的东西来获取项目到下拉列表;

 var memberAdminOrMajor = Db.Members
     .Where(m => m.MemberType == MemberTypeForReeve.BelediyeBaskani)
     .OrderBy(m => m.Id)
     .Select(m => m.Mail)
     .ToList();

 var memberBM = Db.Members
     .Where(m => m.MemberType == MemberTypeForReeve.SahaElemanı)
     .OrderBy(m => m.Id)
     .Select(m => m.Mail)
     .ToList();

我如何获得var list = new List<DropDownListItem>(); var MembersForDrop = Db.Members.OrderBy(o => o.Sira) .Where(p=>p.MemberType == (MemberTypeForReeve)2); foreach (var temp in MembersForDrop) { list.Add(new DropDownListItem() { Text = temp.Name + "." + temp.SurName, Value = temp.Id }); } memberAdminOrMajor

1 个答案:

答案 0 :(得分:1)

假设您在单个视图中需要两个列表。因此,创建一个包含列表和其他数据的视图模型:

public class MyViewModel
{
    public IEnumerable<SelectListItem> MemberAdminOrMajors { get; set; }
    public IEnumerable<SelectListItem> MemberBMs { get; set; }

    public int SelectedAdmin {get; set;}
    public int SelectedBM {get; set; }

    // other data
}

在您的操作方法中填写视图模型并传递给视图:

public ActionResult MyAction()
{
     var model=new MyViewModel
     {
         MemberAdminOrMajors = Db.Members
             .Where(m => m.MemberType == MemberTypeForReeve.BelediyeBaskani)
             .OrderBy(m => m.Id)
             .Select(m => new SelectListItem{ Text=m.Mail, Value=m.Id });

         MemberBMs= Db.Members
             .Where(m => m.MemberType == MemberTypeForReeve.SahaElemanı)
             .OrderBy(m => m.Id)
             .Select(m => new SelectListItem{ Text=m.Mail, Value=m.Id });

         // collectiong other data
     }
     return View(model);
} 

查看:

@model MyNamespace.MyViewModel
@using (Html.BeginForm())
{
    @Html.DropDownListFor(model => model.SelectedAdmin, Model.MemberAdminOrMajors)
    @Html.DropDownListFor(model => model.SelectedBM, Model.MemberBMs)

    <input type="submit" value="submit" class="btn btn-default" />
}

现在,如果您有这样的回复操作,您可以获得用户选择的值:

[HttpPost]
public ActionResoult MyAction(MyViewModel model)
{
    var adminId = model.SelectedAdmin;
    var bmId = model.SelectedBM;
    // rest of code
}

但如果你想在1个列表中列出marge 2列表,你可以写:

var newList=Db.Members
    .Where(m => m.MemberType == MemberTypeForReeve.BelediyeBaskani
        || m.MemberType == MemberTypeForReeve.SahaElemanı)
    .OrderBy(m => m.Id)
    .Select(m => new SelectListItem{ Text=m.Mail, Value=m.Id })
    .ToList();

您还可以concat列出:

var newList=memberAdminOrMajor.Concat(memberBM)
    .Select(m => new SelectListItem{ Text=m.Mail, Value=m.Id });