Asp.net mvc 4 asp.net mvc 4 dropdownlist不返回值

Asp.net mvc 4 asp.net mvc 4 dropdownlist不返回值,asp.net-mvc-4,Asp.net Mvc 4,我有两个模型-问题和类别- public class Question { [ScaffoldColumn(false)] public int QuestionId { get; set; } [Required] public string QuestionText { get; set; } [Required] public string AnswerA { get; set; } [Required] public str

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

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; }
}
我有以下创建方法-

// 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);
    }
我对提出新问题的看法如下: @模型测验

@{
    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")
}
@{
ViewBag.Title=“创建”;
}
@使用(Html.BeginForm()){
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
问题:
@LabelFor(model=>model.QuestionText)
@EditorFor(model=>model.QuestionText)
@Html.ValidationMessageFor(model=>model.QuestionText)
@LabelFor(model=>model.AnswerA)
@EditorFor(model=>model.AnswerA)
@Html.ValidationMessageFor(model=>model.AnswerA)
@LabelFor(model=>model.AnswerB)
@EditorFor(model=>model.AnswerB)
@Html.ValidationMessageFor(model=>model.AnswerB)
@LabelFor(model=>model.AnswerC)
@EditorFor(model=>model.AnswerC)
@Html.ValidationMessageFor(model=>model.AnswerC)
@LabelFor(model=>model.AnswerD)
@EditorFor(model=>model.AnswerD)
@Html.ValidationMessageFor(model=>model.AnswerD)
@LabelFor(model=>model.Correct)
@EditorFor(model=>model.Correct)
@Html.ValidationMessageFor(model=>model.Correct)
@LabelFor(model=>model.categoryId)
@Html.DropDownListFor(model=>model.categoryId,(SelectList)ViewBag.categoryId)
@Html.ValidationMessageFor(model=>model.categoryId)

} @ActionLink(“返回列表”、“索引”) @节脚本{ @Scripts.Render(“~/bundles/jqueryval”) }
因此,问题在于,尽管可以创建问题,但dropdownlist中的categoryId始终为空

我尝试了很多方法,从尝试直接访问dropdownlist到创建不同的viewmodel。但是,它们都没有按要求工作。另外,我的代码遵循在线提供的教程。我不知道有什么不同


请帮我找出代码中的错误

我们可能不得不缩小范围,我感觉从ViewBag中正确读取模型出了问题。尝试将您的
创建
操作替换为以下操作,其中您的自定义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时也要更新您的视图。

请删除问题对象并使用fromcollection,它将为您提供来自post请求的所有信息。一定是有拼写错误。我不太明白。。。你能确切地告诉我该怎么做吗?好的,我试过使用FormCollection,但它只返回字符串形式的属性。请尝试使用@Html.DropDownListFor(model=>model.Category.CategoryId…@Madhu formcollection也应该提供字符串和值。你能把你得到的详细信息转储吗。woohoo!这很有效!不过有一个问题-只填充了question.Category.CategoryId,question.CategoryId和question.Category.Name为空。我能够获得此信息。但是ModelState仍然为空l为question.Category.Name显示了一个错误。是否有方法重置ModelState错误?或者我是否应该不必麻烦,直接执行保存?错误是什么?您可以通过调用以下命令来清除ModelState错误…if(ModelState.ContainsKey(“{key}”))ModelState[“{key}]”。errors.clear();您可以通过不将Category.Name标记为required@ElliotSchmelliot我得到的错误是Category.Name为null。我将尝试清除该错误,但如何排除Category.Name未被填充的原因?@nakor yes,删除所需的修复了它的modelstate错误,但我需要为categ逻辑控制器和模型
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);
}