首页 > 解决方案 > 部分页面 Asp.NET IEnumerable 中没有 ViewData

问题描述

我在尝试在索引页面中加载部分视图时遇到问题,该站点显示的错误如下:

没有具有键“QuestionType”的“IEnumerable”类型的 ViewData 项,基本上问题似乎出在下拉 html 中。

这是我的部分:

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

我的问题控制器

public ActionResult Create()
    {
        ViewBag.QuestionType = new SelectList(db.QuestionTypes, "Id", "Name");
        return View();
    }

    // POST: MyQuestions/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Title,Description,QuestionDate,Tags,QuestionType")] MyQuestion myQuestion)
    {
        if (ModelState.IsValid)
        {
            db.MyQuestions.Add(myQuestion);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.QuestionType = new SelectList(db.QuestionTypes, "Id", "Name", myQuestion.QuestionType);
        return View(myQuestion);
    }

这就是我所说的部分:

<div class="modal-body">
            @Html.Partial("_CreatePartial", new MyWebAppInMVC.Database.MyQuestion())
        </div>

在部分的顶部,我使用以下行:

@using (Html.BeginForm("Create", "MyQuestions", FormMethod.Post, new { id = "AddModal" }))

我的代码有什么问题?

标签: c#asp.netasp.net-mvcentity-framework

解决方案


简单地写你@Html.DropDownList如下:

@Html.DropDownList("QuestionType", ViewBag.QuestionType as SelectList,"Select Question Type", htmlAttributes: new { @class = "form-control" })

推荐阅读