将视图包传递给@Dropdownlist [英] Passing a viewbag to a @Dropdownlist

查看:55
本文介绍了将视图包传递给@Dropdownlist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将视图包传递给DropDownList,但无法正常工作.

I'm trying to pass view bag to a DropDownList but is not working.

下拉列表错误

视图

   <div class="form-group">
            @Html.LabelFor(model => model.BanhoTosaId, "BanhoTosaId", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
               @Html.DropDownList("TransporteId", ViewBag.BanhoTosaId, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.BanhoTosaId, "", new { @class = "text-danger" })
            </div>
        </div>

控制器

 // GET: AgendaBTs/Create
        public ActionResult Create(int id, int pet)
        {

            ViewBag.BanhoTosaId = new SelectList(db.BanhoTosas, "BanhoTosaId", "Tipo");
            ViewBag.ClienteId = new SelectList(db.Clientes, "ClienteId", "Nome", id);
            ViewBag.PetId = new SelectList(db.Pets, "PetId", "PetNome", pet);
            ViewBag.TransporteId = new SelectList(db.Transportes, "TransporteId", "Tipo");

            if (ViewBag.BanhoTosaId != null && ViewBag.SelectedValue != null)
            {
                BanhoTosa BT = db.BanhoTosas.Find(ViewBag.BanhoTosaId);
                Transporte TS = db.Transportes.Find(ViewBag.TransporteId);
                decimal valorSoma = BT.Valor + TS.Valor;
                ViewBag.Total = valorSoma;
            }
            else
            {
                ViewBag.Total = 0;
            }

            return View();
        }

如果我这样让下拉菜单@ Html.DropDownList("TransporteId",null,htm....如果在控制器中,则抛出else方法.

If I let the dropdown this way @Html.DropDownList("TransporteId",null, htm.... the if in the controller you throw the else method.

我该怎么解决?

推荐答案

您首先需要从要填充列表的数据中创建一个列表,如下所示:

you first need to make a list from data you wanna fill list by it like that :

List<Category> CatList = db.Categories.ToList();

然后使用ViewBag:

and then use a ViewBag :

 ViewBag.CategoriesList = new SelectList(CatList, "CategoryID", "CategoryName");

之后,您将查看并编写:

after that you will going to view and write:

     <div class="form-group" style="margin-left:85px">
                    <div class="col-md-10">
  @Html.DropDownListFor(model => model.CategoryID, ViewBag.CategoriesList as SelectList,
             "Select Category", new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })
                  
                    </div>
                </div>

这个我之前从事过的项目的示例

this example from project i worked on it before

这篇关于将视图包传递给@Dropdownlist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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