表格提交后保留模型

时间:2013-09-28 16:14:49

标签: c# asp.net-mvc-3

我有以下用于测验的模型,我正在尝试提交表单并将现有模型传递回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而不包含“问题”或“解释”属性。如何告诉我的观点将收到的原始模型传递回“提交”操作?

2 个答案:

答案 0 :(得分:3)

首次显示索引时,您的问题和说明会正确显示。 然后您提交表单,问题和解释不会进入控制器操作。

这是因为您的FORM没有包含问题和解释的输入字段。

将此添加到您的表单:

@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>
}

答案 1 :(得分: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);
}

希望这会有所帮助!!