简体   繁体   English

MVC视图不要在下拉列表中选择空值

[英]MVC View do not select null value in dropdownlist

if I edit an element it is possible that the carrierId is null. 如果我编辑元素,则carrierId可能为null。 The controller send the null value. 控制器发送空值。 But the view selects the first available value from the dropdownlist and not the null value. 但是视图从下拉列表中选择第一个可用值,而不是空值。

I want that if the value is null no element in die dropdownlist is preselected. 我希望如果该值为null,则不选择dropdownlist中的任何元素。

View: 视图:

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

Controller: 控制器:

public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Model model= ModelService.Get(id);
        if (model== null)
        {
            return HttpNotFound();
        }
        ViewBag.CarrierList = new SelectList(db.User, "ID", "Name", model.CarrierID);

        return View(model);
    }

Add "" to DropDownListFor 在DropDownListFor中添加“”
become like this: 变成这样:

@Html.DropDownListFor(model => model.CarrierID, (SelectList)ViewBag.CarrierList,"", htmlAttributes: new { @class = "form-control" })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM