Html.DropDownList所选值不起作用(将构造函数与IEnumerable< SelectListItem>一起使用) [英] Html.DropDownList Selected Value Not Working (Using Constructor with IEnumerable<SelectListItem>)

查看:74
本文介绍了Html.DropDownList所选值不起作用(将构造函数与IEnumerable< SelectListItem>一起使用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,其中所选值不适用于Html.DropDownList帮助器方法.见下文:

I have an issue where the selected value is not working for the Html.DropDownList helper method. See below:

这是我的控制器:

public ActionResult Edit(int id = 0)
{
    NewsEvent item = GetItem(id);
    ViewBag.NewsItemId = new SelectList(ViewBag.NewsItemId.Items, "Id", "Name", item.NewsItemId);

    return View(item);
}

这是我的观点:

@Html.DropDownList("NewsItemId",ViewBag.NewsItemId as SelectList, string.Empty,
                           new { @class = "form-control" })

但是,当我通过视图尝试以下方法时,它会起作用:

However when I try the below in by view it works:

@Html.DropDownList("NewsItemId", string.Empty)

以下内容也可以使用,但是由于字段名称与模型不匹配,因此无法正确发布.

The below also works but since the field name does not match the model, it will not post correctly.

@Html.DropDownList("NewsItemIdDrop",ViewBag.NewsItemId as SelectList, string.Empty,
                           new { @class = "form-control" })

我需要使用第一个选项的原因是为了可以将class属性添加到控件中.

The reason I need to use the first option is so that I can add the class attribute to the control.

有人可以帮助我了解我在做什么错吗?

Could someone help me understand what I am doing wrong?

推荐答案

您在这里遇到相同的问题:

You have the same problem here:

未选择值的DropDownList

问题在您的ViewBag属性名称中.由于它与模型中的属性相同,因此将无法使用.您应该将ViewBag道具的名称更改为其他名称,例如:

Problem is in your ViewBag property name. Because it is same as your property in Model it will not work. You should just change name of your ViewBag prop to something else, like:

ViewBag.NewsItemList = new SelectList(ViewBag.NewsItemId.Items, "Id", "Name", item.NewsItemId);

并在视图上

@Html.DropDownList("NewsItemId",ViewBag.NewsItemList as SelectList, string.Empty,
                           new { @class = "form-control" })

这篇关于Html.DropDownList所选值不起作用(将构造函数与IEnumerable< SelectListItem>一起使用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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