使用 ASP.NET MVC ViewBag 和 DropDownListfor 时遇到困难 [英] Having difficulty using an ASP.NET MVC ViewBag and DropDownListfor

查看:21
本文介绍了使用 ASP.NET MVC ViewBag 和 DropDownListfor 时遇到困难的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的难点是如何将 ViewBagDropdownListFor 一起使用?

My difficulty is how to use ViewBag with DropdownListFor?

在我的控制器中,我有:

In my controller I am having:

TestModel model = new TestModel();
ViewBag.Clients = model.Clients;
ViewBag.StatusList = model.StatusList;
ViewBag.enumStatus = model.enumStatus;
ViewBag.intClient = model.intClient;

在我的测试模型中

public SelectList Clients { get; set; }       
public SelectList StatusList { get; set; }
public ActiveStatus enumStatus { get; set; }
public int? intClient { get; set; }

在我看来

我想使用 DropDownListFor 来显示 ViewBag 值,我该怎么做?

I want to use DropDownListFor to display the ViewBag values, how can I do that?

推荐答案

你可以这样做:

@Html.DropDownListFor(x => x.intClient, ViewBag.Clients)

但我建议您避免使用 ViewBag/ViewData 并从您的视图模型中获利:

But I would recommend you to avoid ViewBag/ViewData and profit from your view model:

public ActionResult Index()
{
    var model = new TestModel();
    model.Clients = new SelectList(new[]
    {
        new { Value = "1", Text = "client 1" },
        new { Value = "2", Text = "client 2" },
        new { Value = "3", Text = "client 3" },
    }, "Value", "Text");
    model.intClient = 2;
    return View(model);
}

并在视图中:

@Html.DropDownListFor(x => x.intClient, Model.Clients)

这篇关于使用 ASP.NET MVC ViewBag 和 DropDownListfor 时遇到困难的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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