2

我有以下用于测验的模型,我正在尝试提交表单并将现有模型传递回 Action,因为它已经在 Index 操作中初始化。

public class QuizModel
{
    private List<string> _Responses;

    public List<string> Responses
    {
        get
        {
            if (_Responses == null)
            {
                _Responses = new List<string>() { "Response A", "Response B", "Response C", "Response D" };
            }
            return _Responses;
        }
    }

    public int? SelectedIndex { get; set; }

    public string Question { get; set; }
}

使用以下视图:

<div class="title">Question</div>
<span id="question">@Model.Question</span>
@if (!Model.UserHasAnswered)
{
using (Html.BeginForm("Submit", "Quiz", FormMethod.Post))
{
    for (int i = 0; i < Model.Responses.Count; i++)
    {
        <div class="reponse">@Html.RadioButtonFor(m => m.SelectedIndex, i)@Model.Responses[i]</div>
    }
    <input type="submit" value="This is the value" />                              
}
}
else
{
    <div id="explanation">@Model.Explanation</div>
}

和控制器...

//
    // GET: /Quiz/

    public ActionResult Index()
    {
        QuizModel model = new QuizModel()
        {
            Question = "This is the question",
            Explanation = "This is the explanation",
            UserHasAnswered = false
        };

        return PartialView(model);
    }

    //
    // POST: /Quiz/Submit
    [HttpPost]
    public ActionResult Submit(QuizModel model)
    {
        if (ModelState.IsValid)
        {
            int? selected = model.SelectedIndex;

            model.UserHasAnswered = true;
        }

        return View("Index", model);
    }

当模型进入提交操作时,它只包含 SelectedIndex 而不是 Question 或 Explanation 属性。如何告诉我的视图将它收到的原始模型传递回提交操作?

4

2 回答 2

3

当您第一次显示索引时,您的问题和解释会正确显示。然后你提交表单,问题和解释并没有进入控制器动作。

那是因为您的表格没有包含问题和解释的输入字段。

将此添加到您的表单中:

@Html.HiddenFor(x => x.Question)
@Html.HiddenFor(x => x.Explanation)

如果用户可以编辑解释,而不是为其添加隐藏,请执行以下操作:

@Html.TextAreaFor(x => x.Explanation)

请记住:您需要发送到控制器的所有信息都需要在 FORM 中的 INPUTS 中。

这样,您的视图将变为:

<div class="title">Question</div>
<span id="question">@Model.Question</span>
@if (!Model.UserHasAnswered)
{
using (Html.BeginForm("Submit", "Quiz", FormMethod.Post))
{
    @Html.HiddenFor(x => x.Question)
    @Html.HiddenFor(x => x.Explanation)
    for (int i = 0; i < Model.Responses.Count; i++)
    {
        <div class="reponse">@Html.RadioButtonFor(m => m.SelectedIndex, i)@Model.Responses[i]</div>
    }
    <input type="submit" value="This is the value" />                              
}
}
else
{
    <div id="explanation">@Model.Explanation</div>
}
于 2013-09-28T17:20:29.643 回答
0

我相信您的index操作在您的场景中应该如下所示:

public ActionResult Index(QuizModel model)
{
    if(model == null) 
    {
        model = new QuizModel()
        {
            Question = "This is the question",
            Explanation = "This is the explanation",
            UserHasAnswered = false
        };
    }

    return PartialView(model);
}

希望这会有所帮助!

于 2013-09-28T16:20:19.890 回答