Mvc ID未提交

时间:2017-03-23 11:24:02

标签: c# asp.net-mvc razor

我有一个下拉列表,如下所示,试图将我的id传递给控制器​​,但始终为0

 <div class="form-group">
        @Html.LabelFor(model => model.SagsTypersId, "SagsTypeId1", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("SagsTypeId1", null, htmlAttributes: new {
           @class = "selectpicker",
           data_show_subtext = "true",
           data_live_search = "true"
       })
            @Html.ValidationMessageFor(model => model.SagsTypersId, "", new { @class = "text-danger" })
        </div>
    </div>

继承人是我的控制者Get。

 public ActionResult Create()
    {

        ViewBag.SagsTypeId1 = new SelectList(db.SagsTypers, "Id", "SagsTyper");

        return View();
    }

这里是控制器帖子

 public ActionResult Create(Sag sag)
    {

        if (ModelState.IsValid)
        {
            db.Sags.Add(sag);
            db.SaveChanges();
            return RedirectToAction("Index");
        }


        return View(sag);
    }

总结一下,我的问题是Sags.SagsTypersId在尝试提交时为0。似乎找不到错误。

祝你好运 约翰尼。

2 个答案:

答案 0 :(得分:0)

您没有将下拉列表附加到模型,使用@Html.DropDownListFor代替@Html.DropDownList

其中SagsTypersList是列表包含SagsTypersID&amp; SagsTyperName

@Html.DropDownListFor(model => model.SagsTypersId, 
          new SelectList(SagsTypersList, "SagsTypersID", "SagsTyperName"), htmlAttributes: new {
           @class = "selectpicker",
           data_show_subtext = "true",
           data_live_search = "true"
       })

答案 1 :(得分:0)

更改

  @Html.DropDownList("SagsTypeId1", null, htmlAttributes: new {
           @class = "selectpicker",
           data_show_subtext = "true",
           data_live_search = "true"
       })

  @Html.DropDownList("SagsTypeId", null, htmlAttributes: new {
           @class = "selectpicker",
           data_show_subtext = "true",
           data_live_search = "true"
       })

只需使用强类型的html帮助器:

@Html.DropDownListFor(model => model.SagsTypersId, 
          new SelectList(SagsTypersList, "SagsTypersID", "SagsTyperName"), htmlAttributes: new {
           @class = "selectpicker",
           data_show_subtext = "true",
           data_live_search = "true"
       })