asp.net mvc 4 dropdownlist不返回值

时间:2013-08-08 02:31:44

标签: asp.net-mvc-4

我有2个模型 - 问题和类别 -

public class Question
{
    [ScaffoldColumn(false)]
    public int QuestionId { get; set; }
    [Required]
    public string QuestionText { get; set; }
    [Required]
    public string AnswerA { get; set; }
    [Required]
    public string AnswerB { get; set; }
    [Required]
    public string AnswerC { get; set; }
    [Required]
    public string AnswerD { get; set; }
    [Required]
    public int Correct { get; set; }

    [ForeignKey("Category")]
    [Display(Name = "Category")]
    [Required]
    public int categoryId;

    //Navigation property
    public virtual Category Category { get; set; }
}

public class Category
{
    [ScaffoldColumn(false)]
    public int CategoryId { get; set; }
    [Required]
    public string Name { get; set; }

    public virtual ICollection<Question> Question { get; set; }
}

在我的QuestionController中,我添加了代码,以便能够访问视图中下拉列表的可用类别 -

 private void PopulateCategoryDropDownList(object selectedCategory = null)
    {
        var categoryQuery = from c in db.Categories
                               orderby c.Name
                               select c;
        ViewBag.categoryId = new SelectList(categoryQuery, "CategoryId", "Name", selectedCategory);
    }

我有以下创建方法 -

// GET: /Question/Create

    public ActionResult Create()
    {
        PopulateCategoryDropDownList();
        return View();
    }

    //
    // POST: /Question/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Question question)
    {
        try
        {
            var errors = ModelState.Values.SelectMany(v => v.Errors);
            if (ModelState.IsValid)
            {
                db.Questions.Add(question);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        catch (DataException dex)
        {
            ModelState.AddModelError("",dex.Message);
        }
        PopulateCategoryDropDownList(question.Category.CategoryId);
        return View(question);
    }

我对创建新问题的看法如下 -     @model Quiz.Models.Question

@{
    ViewBag.Title = "Create";
}

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

<fieldset>
    <legend>Question</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.QuestionText)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.QuestionText)
        @Html.ValidationMessageFor(model => model.QuestionText)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.AnswerA)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.AnswerA)
        @Html.ValidationMessageFor(model => model.AnswerA)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.AnswerB)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.AnswerB)
        @Html.ValidationMessageFor(model => model.AnswerB)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.AnswerC)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.AnswerC)
        @Html.ValidationMessageFor(model => model.AnswerC)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.AnswerD)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.AnswerD)
        @Html.ValidationMessageFor(model => model.AnswerD)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Correct)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Correct)
        @Html.ValidationMessageFor(model => model.Correct)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.categoryId)
    </div>

    <div class="editor-field">
        @Html.DropDownListFor(model => model.categoryId,(SelectList)ViewBag.categoryId)
        @Html.ValidationMessageFor(model => model.categoryId)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

所以,问题在于虽然可以创建问题,但下拉列表中的categoryId始终为null。

enter image description here

The first image shows the create page, and the second one is the create method on breakpoint

我尝试了很多东西,从尝试直接访问下拉列表到创建不同的viewmodel。但是,它们都不能按要求工作。此外,我的代码遵循在线提供的教程。我无法弄清楚有什么不同。

请帮我在代码中找到错误。

1 个答案:

答案 0 :(得分:0)

我们可能不得不缩小范围,我感觉从ViewBag正确读取的模型出了问题。尝试使用以下内容替换Create操作,您的自定义ViewBag填充功能已被删除:

public ActionResult Create() {
        ViewBag.categoryId = new SelectList(db.Categories, "CategoryId", "Name");
        return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Question question) {
    try {
        var errors = ModelState.Values.SelectMany(v => v.Errors);
        if (ModelState.IsValid) {
            db.Questions.Add(question);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    } catch (DataException dex) {
        ModelState.AddModelError("",dex.Message);
    }
    ViewBag.categoryId = new SelectList(db.Categories, "CategoryId", "Name", question.Category.CategoryId);
    return View(question);
}

这是否正确运行?

如果这不起作用,则必须是模型绑定问题。我能想到的最后一件事就是改变ViewBag调用以实现字段Category而不是CategoryId。在制作DropDownList时也会更新您的视图。