我如何使用mymodel对象检索下拉列表 [英] How do i retrive dropdownlist using mymodel object

查看:55
本文介绍了我如何使用mymodel对象检索下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用mymodel对象检索视图下拉列表

How do i retrive in view dropdownlist using mymodel object

    List<object> mymodel = new List<object>();

        mymodel.Add(db.Events.ToList());
        mymodel.Add(db.Purposes.ToList());
        return View(mymodel);

推荐答案

我建议为您的视图创建一个模型,并在此过程中实施其他一些最佳实践.解决方案的各个方面如下所示:

I would recommend creating a Model for your view and also implement few other best practices on the way. Various aspects of the solution will look like below:

  1. Models 文件夹中,为您的视图创建一个模型,如下所示:

  1. In Models folder create a model for your view as below:

public class MyViewModelClass
{
    public IEnumerable<SelectListItem> Events { get; set; }

    public IEnumerable<SelectListItem> Purposes { get; set; }
}

  • 在您的 Controller 中,填充视图的模型并将其返回到视图,如下所示.请注意,您应该为下拉列表选择两个属性.值"将位于与下拉列表中每个项目相关的场景值后面,文本"将显示给最终用户.另外请注意,我返回的是SelectListItem,以后可以将其与下拉列表绑定.

  • In your Controller, populate the model for the view and return it to the view as shown below. Note that you should select the two properties for the drop down list. "Value" which will be behind the scene value associated to each item in the drop down and "Text" which will be shown to the end user. Also note that I am returning SelectListItem which I can then later bind with the Drop down list.

    MyViewModelClass mymodel = new MyViewModelClass();
    
    mymodel.Events = db.Events.ToList().Select(x =>
                        new SelectListItem
                        {
                            Value = x.EventID.ToString(),
                            Text = x.EventName
                        });
    mymodel.Purposes = db.Purposes.ToList().Select(x =>
                        new SelectListItem
                        {
                            Value = x.PurposeID.ToString(),
                            Text = x.PurposeName
                        });
    
    return View(mymodel);
    

  • 现在是最后一部分,即视图.您需要在此处实现三件事:

  • Now comes the last part, your View. You need to implement three things here:

    • 告知视图需要什么样的模型.
    • 创建HTML表单
    • 生成下拉列表

    事件"下拉列表的完整视图如下所示:

    The complete view will look like below for Events drop down:

        @model MyViewModelClass
    
        @{
            ViewBag.Title = "Home Page";
        }
    
        <div>
        @using (Html.BeginForm())
        {
                    @Html.DropDownListFor(m=>m.Events,Model.Events,"--select--")
        }
        </div>
    

    这篇关于我如何使用mymodel对象检索下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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