如何将列表从控制器发送到视图中的DropDownList? [英] How can i Send my list From my controller to my DropDownList in the View?

查看:52
本文介绍了如何将列表从控制器发送到视图中的DropDownList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道它应该看起来像这样

i know it should look like this

@Html.DropDownList("yourDropName", listItems, new { @class = "form-control" })

但是我不知道该怎么办在我的控制器中,我向其传递了一个列表,该列表已在我的模型层中初始化,在View_Model中,我只是从模型中获取它并将其传递给我的控制器

but i can't figure it out how should i do it in my controller i passed a list to it which was initialized in my model layer and in my View_Model i simply get it from model and pass it to my controller

这是我的模型中

    public List<int?> TeamId()
    {
        ListTeam = new List<int?>();
        using (var context = new EF_Model.DigikalaHREntities())
        {
            //var p = context.Members.Any(c => c.TeamId);
            var p = from c in context.Members
                    where c.TeamId.HasValue
                    select new { c.TeamId };
            return p.Select(m => m.TeamId).ToList();
        }
    } 

我的视图模型中有2个类,第一个是带有某些数据注释的实体,第二个是从模型中获取方法的类所以这是我的View模型层(我没有将此层传递给View)

i have 2 Classes in my view model first one is just entities with some Data Annotation and second one is the class which i get my methods from my Model so this is my View model layer(i didn't passed this one to my View)

     public List<int?> GetTeamId()
    {
        Ref_CRUD = new Models.CRUD.Member();
        return Ref_CRUD.TeamId();
    } 

我的控制器

  #region [- Get -]
    public ActionResult Create()
    {
        Ref_Member = new View_Model.Buisiness.Member();
        return View(Ref_Member.GetTeamId());
    }

这是我的视图

@model DigikalaHR.View_Model.Entitys.Member
 . 
 .
 .
 .
 <div class="form-group">
        @Html.LabelFor(model => model.TeamId, "TeamId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">       
 //don't know how to use one of These  two lines and which one i should use 
            @*@Html.DropDownList("TeamId",new SelectList(enum.(typeof())),htmlAttributes: new {@class="form-control" })*@
           @*@Html.DropDownListFor(m => m.TeamId,new SelectList(Enum.GetValues(typeof(id))),"GetTeamId")*@
            @Html.ValidationMessageFor(model => model.TeamId, "", new { @class = "text-danger" })
        </div>
    </div>

如何将我的列表从控制器发送到视图中的DropDownList?

How can i Send my list From my controller to my DropDownList in the View?

推荐答案

我认为您在这里混淆了一些事情.您的视图模型应该是特定于该视图的模型,而这些模型只是用于数据传输的哑POCO类.没有业务逻辑,或者对您的数据访问技术/实体类一无所知.请勿将视图模型与实体类混合使用.

I think you are mixing things up here. Your view models should be models specific to the view and those are simply dumb POCO classes for data tranfer. No business logic or those has no idea about what your data access technology / entity classes are. Do not mix view models with entity classes.

因此,在您的情况下,如果您的视图是要创建成员,则应该有一个视图模型,该模型具有该视图中绝对需要的属性(对于输入元素)

So in your case, if your view is to create a member, you should have a view model with properties which are absolutely needed in the view (for input elements)

public class CreateMemberVm
{
   public string FirstName { set;get;}
   public int? SelectedTeamId { set;get;}
   public List<SelectListItem> Teams { set;get;}
   // Add other properties as needed by the view. 
}

根据视图的需要向视图模型添加其他属性.没有理由盲目地将实体类中的所有属性添加到视图模型中.

Add other properties to your view model as needed by the view. There is no reason to blindly add all the properties from your entity class to your view models.

现在,在GET操作中,您将初始化该视图模型的对象,并在 Teams 属性中添加 SelectListItem 对象列表(我们将在视图中使用该对象)构建SELECT元素选项)并将对象发送到vieww

Now in your GET action, you initialize an object of this view model, popualte the Teams property with a list of SelectListItem objects (we will use this in the view to build the SELECT element options) and send the object to the vieww

public ActionResult Create()
{
   var vm = new CreateMemeberVm();
   vm.Teams = GetTeamItems();
   return View(vm);
}
public List<SelectListItem> GetTeamItems()
{
    using (var db = new EF_Model.DigikalaHREntities())
    {
        return db.Teams
                 .Select(a=>new SelectListItem { 
                                                 Value=a.TeamId.ToString(),
                                                 Text=a.TeamName
                                               })
                  .ToList();
    }
}

现在在您的视图中(应严格将其键入到我们的视图模型中),您可以使用 DropDownListFor 帮助器方法来呈现SELECT元素.

Now in your view, which should be strongly typed to our view model, you can use the DropDownListFor helper method to render the SELECT element.

@model CreateMemberVm
@using(Html.BeginForm())
{
   @Html.LabelFor(a=>a.FirstName)
   @Html.TextBoxFor(a=>a.FirstName)

   @Html.LabelFor(a=>a.SelectedTeamId)
   @Html.DropDownListFor(m => m.SelectedTeamId, Model.Teams, "Select team")
   <input type="submit" />
}

您可以使用与HttpPost操作方法的参数相同的视图模型类,现在当用户在填写表单, SelectedTeamId 属性和 FirstName 后提交表单时>属性将从表单数据中填充,您可以使用这些属性将其保存到表格中

You can use the same view model class as the parameter of your HttpPost action method and now when user submits the form after filling the form, the SelectedTeamId property and the FirstName property will be populated from the form data and you can use those to save to your table

[HttpPost]
public ActionResult Create(CreateMemeberVm model)
{
  // check model.FirstName and model.SelectedId
  // to do : Save as needed
  // to do : return something
}

如果要在视图中预选择一个项目(对于编辑成员用例),只需将视图模型的 SelectedTeamId 属性设置为您拥有的任何内容在您的数据库中

If you want to preselect an item in your view (for the case of edit member use case), all you have to do is, set the SelectedTeamId property of your view model to whatever you have in your db

public ActionResult Edit(int id)
{
   var m = db.Members.Find(id);
   var vm = new CreateMemeberVm() { FirstName = m.FirstName, SelectedTeamId=m.TeamId};
   vm.Teams = GetTeamItems();
   return View(vm);
}

这篇关于如何将列表从控制器发送到视图中的DropDownList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆