c# - MVC 下拉列表未获取 Controller 中的值

标签 c# asp.net .net asp.net-mvc

我正在使用 Razor 创建一个下拉列表,填充模型列表,然后将此列表传递到 View 以填充下拉列表。下拉列表已正确创建,但是当我将值发布到 Controller 的创建操作时,我没有获得下拉列表值。

模型,在IdCarBrand中我返回下拉值,谁填充列表DropDownList:

public class CarModelModel
{
    public int IdCarBrand { get; set; }
    //Drop down
    public IEnumerable<SelectListItem> DropDownList { get; set; }
}

然后我用这个方法填充列表,服务只需访问数据库:

        public IEnumerable<SelectListItem> GetItemsDropDown()
       {
        SelectListItem listItem = null;
        CarBrandService service = new CarBrandService();
        var itemsList = service.GetAll().Select(x => 
            new SelectListItem{
                Value = x.Id.ToString(),
                Text = x.Name
            });

        return new SelectList(itemsList, "Value", "Text");
       }

并且在 Controller 中我也有默认的创建操作

    public ActionResult Create()
    {

    }

这里是模型变量中的

    public ActionResult Create([Bind(Include = "Id,Name,Description,URL,Email,Img")] CarModelModel brand)
    {
        if (ModelState.IsValid)
        {

            return RedirectToAction("Index");
        }

        return View(brand);
    }

现在在 View 中我有以下代码来创建 dropdrown:

@Html.DropDownListFor(model => model.IdCarBrand, Model.DropDownList, new { htmlAttributes = new { @class = "form-control" } })

渲染的html是:

<select name="IdCarBrand" id="IdCarBrand" htmlattributes="{ class = form-control }" data-val-required="The IdCarBrand field is required." data-val-number="The field IdCarBrand must be a number." data-val="true" class="valid">
<option value="1">Alfa Romeo</option>
<option value="2">Audi</option>
<option value="3">BMW</option>
<option value="4">Chery</option>
<option value="5">Chrevrolet</option>.......

综上所述,下拉菜单显示得非常完美。 我有两个问题:

1- 在创建操作中,IdCarBrand 返回 null。

2-从视觉上看,下拉列表没有采用类形式控制:

最佳答案

在你的行动中..你没有包含它。

  public ActionResult Create([Bind(Include = "Id,Name,Description,URL,Email,Img,IdCarBrand")] CarModelModel brand)
    {
        if (ModelState.IsValid)
        {

            return RedirectToAction("Index");
        }

    return View(brand);
}

通过创建包含列表,您已将其排除。

对于下拉菜单..修改如下。

@Html.DropDownListFor(model => model.IdCarBrand, Model.DropDownList,new { @class = "form-control" })

关于c# - MVC 下拉列表未获取 Controller 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29054974/

相关文章:

c# - Xamarin Android 发行版

c# - 在 xamarin 中安装 Microsoft.Net.Http 时出错

c# - .Net MAUI : How to select single and multiple items using MVVM and CollectionView

c# - 跨线程操作在 MDIParent 中无效

c# - asp-for 和 if 条件在同一组件中

c# - 改文件名显示不改原名

asp.net - 创建 F# ASP.NET Core Web 应用程序需要什么 Visual Studio 2017 选项?

c# - 在 Asp.net 中显示括号

c# - HttpContext.Current.Cache 是线程安全的吗?

c# - 无法在数据模板内设置 CommandBinding