如何使用DropDownListFor [英] How to use DropDownListFor

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

问题描述

我想在网站上添加下拉列表html控件,并用产品列表填充它.我的Action控制器看起来像

I want to add Drop Down List html control to the web page fill it with products list. My Action controller looks like

public ActionResult Index()
{
    return View(_repository.GetProducts(true));
}

产品模型(Linq to SQL,下面是部分类,其中SelectedId用于下拉选择ID)

Product model (Linq to SQL, below is partial class where SelectedId is for drop down selection id)

public partial class Product
{

    public int SelectedId { get; set; }
}

视图是

@model IQueryable<Entity.Product>


@Html.DropDownListFor(.....)

我不明白如何用Products填充DropDownList,以及如果选择的产品将Id绑定到SelectedId属性.

What I do not understand how to fill up DropDownList with Products and if product selected bind Id to SelectedId property.

推荐答案

您可以这样实现

在您的模型中,您需要类似

In your model you need something like this

public class TestViewModel
{
    public int IdSelected { get; set; }
    public IEnumerable<Person> People { get; set; }
}

在您的控制器中,您需要类似

In your Controller you need something like this

public ActionResult Index()
{
    var people = new List<Person>
    {
        new Person {Id = 1, Name = "krystan"},
        new Person {Id = 2, Name = "Bobby"}
    };

    var theModel = new TestViewModel
    {
        People = people.Select(x => new Person
        {
            Id = x.Id,
            Name = x.Name
        })
    };

    return View(theModel);
}

然后在您的html中(这会因所使用的视图引擎而有所不同,但假设是剃刀)您需要这样的东西

Then in your html (and this varies a bit depending on the view engine being used but lets assume razor) you need something like this

@model MvcApplication3.Models.TestViewModel
@Html.DropDownListFor(x=>x.IdSelected, new SelectList(Model.People, "Id", "Name"))

可以找到更多信息 查看全文

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