MVC 3下拉列表没有绑定到模型

时间:2012-04-15 21:07:44

标签: asp.net-mvc-3 razor

在我的应用程序中,我有一个下拉列表来表示不同的选择。请注意,Paragraph是一个模型,该部分只是模型中的一个字段。

@Html.DropDownList("Sections")

这是我的控制器。

public ActionResult Edit(int id)
{
    var paragraph = db.Paragraphs.Find(id);

    ViewBag.Sections = new SelectList(
        db.Sections.Select(s => new { s.ID, s.Name }),
        "ID", "Name", paragraph.SectionID
    );

    return View(paragraph);
}

[HttpPost]
public ActionResult Edit(Paragraph paragraph, HttpPostedFileBase document)
{
    if (ModelState.IsValid)
    {
        // Do some stuff.
    }

    ViewBag.Sections = new SelectList(
        db.Sections.Select(s => new { s.ID, s.Name }),
        "ID", "Name", paragraph.SectionID
    );

    return View(paragraph);
}

当我提交表单时,下拉列表没有绑定到模型。导致ModelState.IsValid变得虚假并使我的生命变得可怕。有什么建议吗?

编辑:当我提交表单时,我收到以下错误:

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Sections'.

编辑:我尝试提交文件时似乎只收到上述错误。

编辑:型号

public class Paragraph
{
    public int ID { get; set; }

    [Required]
    public int Major { get; set; }

    [Required]
    public int Minor { get; set; }

    [Required(ErrorMessage = "Name is required")]
    [StringLength(4000)]
    public string Name { get; set; }

    public int SectionID { get; set; }
    public virtual Section Section { get; set; }
}

表格:(这是很多。)

<form class="form-horizontal" action="/Paragraph/Edit" method="post" enctype="multipart/form-data">
    <fieldset>
        <div class="control-group">
            <label class="control-label" for="section">Section</label>
            <div class="controls">
                @Html.DropDownList("Sections")
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="major">Major</label>
            <div class="controls">
                <input type="number" class="input-large" name="major" value="@Model.Major" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="minor">Minor</label>
            <div class="controls">
                <input type="number" class="input-large" name="minor" value="@Model.Minor" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="name">Name</label>
            <div class="controls">
                <input type="text" class="input-large" name="name" value="@Model.Name" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="document">Document</label>
            <div class="controls">
                <input type="file" class="input-file" name="document" />
            </div>
        </div>
        <div class="form-actions">
            <input type="submit" class="btn btn-primary" value="Save" />
            <a class="btn" href="/Paragraph/Show/@Model.ID">Cancel</a>
        </div>
    </fieldset>
</form>

5 个答案:

答案 0 :(得分:1)

只是想知道你为什么不使用Html.TextBoxFor等强类型助手?如果需要,您可以使用它们传递可选的html属性

我会制作您的下拉列表

@Html.DropDownListFor(model =>model.SectionID,(IEnumerable<SelectListItem>) ViewBag.Sections) 

其他

@Html.HiddenFor(model =>model.ID)
@Html.TextBoxFor(model =>model.Name)
@Html.TextBoxFor(model =>model.Major)
@Html.TextBoxFor(model =>model.Minor)

文件可以是<input type="file" class="input-file" name="document" />

那应该给你绑定的模型。您将确保获得正确的名称等。此外,我还将ID作为表格的一部分。

答案 1 :(得分:1)

将您的HTML代码更改为:

@Html.DropDownListFor(m => m.SectionID, ViewBag.Sections as SelectList)

如果您没有此页面的模型,请使用以下代码:

@Html.DropDownList("Sections", ViewBag.Sections as SelectList)

答案 2 :(得分:0)

这是迟到的,但迟到总比没有好。当您使用HtmlHelper提供的帮助程序之一时,它会在幕后生成input名称。生成的此名称格式为Model.Field。例如,带有名为“名称”字段的段落将变为Paragraph.Name

接受一个参数的DropDownList定义使用下拉列表的名称作为input的名称。因此,拨打DropDownList("Sections")会创建一个名为“Sections”的input

最后,我决定向Razor承认并使用内置的HTML助手。所以我的下拉列表代码如下:DropDownListFor(vm => vm.Paragraph.SectionID, Models.Sections)

答案 3 :(得分:0)

太奇怪了!我曾经使用

@Html.DropDownList("permissionsID", String.Empty)

它工作正常 - 突然之间,我收到同样的问题。 ddl未在Create(已发布)控制器方法上提交其选定值

所以我用了

@Html.DropDownListFor(model => model.permissionID, (IEnumerable<SelectListItem>)ViewBag.permissionsID)

它工作正常!

然而,我有旧的控制器,直到今天仍然使用旧的方法工作 - 只是它不喜欢它为我的新控制器!

它真的无视逻辑......

答案 4 :(得分:0)

朋友在进行级联下拉列表时遇到了同样的问题

并且没有为什么要绑定父下拉列表。所以我所做的就是以与即将完成相同的方式填充父下拉列表。创建了一个动作,在json上调用它并使用jquery填充它。

我对控制器的行动:

public ActionResult GetStates()
    {
        if (Request.IsAjaxRequest())
        {
            using (MyModel banco = new myModel())
            {

                return Json(new SelectList(banco.SyStates.ToList(), "StateId", "StateName"), JsonRequestBehavior.AllowGet);

            }
        }
        return View();

    }

观点:

      <select id="StateList" name="StateList"></select> 

<script>

   $(document).ready(function () {



         var URL = "/ControllerName/GetStates";
         $.getJSON(URL, function (data) {



         var items = '<option>Selecione o estado</option>';
         $.each(data, function (i, State) {
             items += "<option value='" + State.Value + "'>" + State.Text + "</option>";
             // state.Value cannot contain ' character. We are OK because state.Value = cnt++;

         });
         $('#StateList').html(items);
         //$('#CitiesTrID').show();

     })

 });

获得级联示例: http://blogs.msdn.com/b/rickandy/archive/2012/01/09/cascasding-dropdownlist-in-asp-net-mvc.aspx