模型在子部分页面MVC5上的帖子上变为空

时间:2014-08-06 15:03:11

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

我正在尝试在用户填写表单后获取所有数据,但是当我尝试将模型作为操作参数访问时,我总是将模型设为null。因此,我尝试使用FormCollection,但仍然无法想象如何访问QuestionModel中埋没的PossibleAnswerModel List。非常感谢您的帮助

更新

在阅读了Chris Pratt评论之后,我将所有内容更新为以下但我仍然无法填充TestModel。每次问题(TestModel测试,FormCollection formCollection)都会调用POST索引动作我甚至尝试过放一个[HttpPost]         公共ActionResult问题(TestModel测试,FormCollection formCollection),但也没有填充View数据。请帮忙

///////////////模型//////////////

 [Serializable]
    public class TestModel
    {
        private QuestionModel _currenQuestionModel;

        public int TestID { get; set; }
        public string TestName { get; set; }

        public string Instructions { get; set; }

        public double TestTime { get; set; }

        public QuestionModel CurrenQuestionModel
        {
            get
            {
                if (_currenQuestionModel == null &&
                    Questions != null && 
                    Questions.Count > 0)
                    _currenQuestionModel = Questions.First();

                return _currenQuestionModel;
            }
            set { _currenQuestionModel = value; }
        }

        public List<QuestionModel> Questions { get; set; }
    }

    public class QuestionModel
    {
        public int QuestionID { get; set; }
        public string Question { get; set; }
        public bool HasMultipleAnswers { get; set; }
        public IList<PossibleAnswerModel> PossibleAnswers { get; set; }   
    }

    public class PossibleAnswerModel
    {
        public bool IsSelected { get; set; }
        public string DisplayText { get; set; }
    }
}

//////////////////控制器/////////////////

 public class TestController : Controller
        {
            public ActionResult Index(int id)
            {
                var model = _testColletion.FirstOrDefault(r => r.TestID == id);
                return View(model);
            }

            [ChildActionOnly]
            [HttpGet]
            public ActionResult Questions(TestModel test)
            {
                var testModel = _testColletion.Single(r => r.TestID == test.TestID);
                return PartialView("_Start", testModel);
            }

            [HttpPost]
            public ActionResult Questions(TestModel test, FormCollection formCollection)
            {
                var q = formCollection.Count >2 ?  formCollection.GetValues(1):null;
                var testModel = _testColletion.FirstOrDefault(r => r.TestID == test.TestID);

                //if (questionID == 0)
                //{
                //    testModel.CurrenQuestionModel = testModel.Questions.First();
                //}
                if (!string.IsNullOrWhiteSpace(Request["next"]))
                {
                    var nextQuestionIndex =
                        testModel.Questions.FindIndex(r => r.QuestionID == testModel.CurrenQuestionModel.QuestionID) + 1;
                    testModel.CurrenQuestionModel = testModel.Questions[nextQuestionIndex];
                }
                else if (!string.IsNullOrWhiteSpace(Request["prev"]))
                {
                    var prevQuestionIndex =
                       testModel.Questions.FindIndex(r => r.QuestionID == testModel.CurrenQuestionModel.QuestionID) - 1;

                    testModel.CurrenQuestionModel = testModel.Questions[prevQuestionIndex];
                }

                return PartialView("_Question", testModel);
            }
            private static List<TestModel> _testColletion = new List<TestModel>()
            {
                new TestModel()
                {
                    TestID = 1,
                    TestName = "ASP.NET",
                    Instructions = "Please choose from appropriate options",
                    TestTime = 2.40,
                     Questions = new List<QuestionModel>()
                    {
                        new QuestionModel(){QuestionID = 1, Question = "Question 1"}
                    }

                },
                new TestModel()
                {
                    TestID = 2,
                    TestName = "ASP.NET MVC",
                    Instructions = "Please choose from appropriate options",
                    TestTime = 1.00,
                    Questions = new List<QuestionModel>()
                    {
                        new QuestionModel(){QuestionID = 1, HasMultipleAnswers=true, Question = "Question 1", PossibleAnswers = new List<PossibleAnswerModel>()
                        {
                            new PossibleAnswerModel(){DisplayText = "Possible Answer 1"},
                            new PossibleAnswerModel(){DisplayText = "Possible Answer 2"},                   
                            new PossibleAnswerModel(){DisplayText = "Possible Answer 3"},   
                            new PossibleAnswerModel(){DisplayText = "Possible Answer 4"},   
                        }},
                        new QuestionModel(){QuestionID = 2, HasMultipleAnswers=true, Question = "Question 2"},
                        new QuestionModel(){QuestionID = 3, HasMultipleAnswers=true, Question = "Question 3"},
                        new QuestionModel(){QuestionID = 4, HasMultipleAnswers=true, Question = "Question 4"},
                        new QuestionModel(){QuestionID = 5, HasMultipleAnswers=true, Question = "Question 5"},
                    }
                },
                new TestModel()
                {
                    TestID = 3,
                    TestName = "ASP.NET Spring",
                    Instructions = "Please choose from appropriate options",
                    TestTime = 1.00,
                     Questions = new List<QuestionModel>()
                    {
                        new QuestionModel(){QuestionID = 1, Question = "Question 1"},
                        new QuestionModel(){QuestionID = 2, Question = "Question 2"},
                        new QuestionModel(){QuestionID = 3, Question = "Question 3"},
                        new QuestionModel(){QuestionID = 4, Question = "Question 4"},
                    }
                },
                new TestModel()
                {
                    TestID = 4,
                    TestName = ".NET C#",
                    Instructions = "Please choose from appropriate options",
                    TestTime = 4.40,
                     Questions = new List<QuestionModel>()
                    {
                        new QuestionModel(){QuestionID = 1, Question = "Question 1"},
                        new QuestionModel(){QuestionID = 2, Question = "Question 2"}
                    }
                }
            };
        }

///////////里面_Question.cshtml局部视图///////////////

@model InterviewQ.MVC.Models.TestModel

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    @*@Html.HiddenFor(r => r.CurrentQuestionID)*@
    <div>
        <br />
        <h4>Question @Model.CurrenQuestionModel.QuestionID</h4>
        <hr />
        <p>@Model.CurrenQuestionModel.Question</p>
    </div>
    <p>
     @if (Model.CurrenQuestionModel.HasMultipleAnswers)
     {
         @Html.Partial("_MultipleAnswerQuestionView", Model.CurrenQuestionModel)
     }
    </p>
    <p>
        @if (Model.CurrenQuestionModel.QuestionID > 0 && Model.CurrenQuestionModel.QuestionID < Model.Questions.Count)
        {
            if (Model.CurrenQuestionModel.QuestionID > 1)
            {
                <input type="submit" class="btn btn-default" value="Previous" name="prev" />
            }

            <input type="submit" class="btn btn-default" value="Next" name="next" />
        }
        @if (Model.CurrenQuestionModel.QuestionID == Model.Questions.Count)
        {
            <input type="submit" class="btn btn-default" value="Finish" name="finish" />
        }
    </p>
}

////////////里面_MultipleAnswerQuestionView.cshtml局部视图///////////////

@model InterviewQ.MVC.Models.QuestionModel

@if (!Model.HasMultipleAnswers)
{
    throw new InvalidOperationException("This answer optioin template doesn't support this type of questions");
}

@for(var i=0; i< Model.PossibleAnswers.Count; i++)
{ 
<div class="row">
    <div class="col-lg-6">
        <div class="input-group">
            <span class="input-group-addon">
                <input type="checkbox" value="@Model.PossibleAnswers[i].IsSelected" name="possibleAnswers">
            </span>
            <p>
                @Model.PossibleAnswers[i].DisplayText
            </p>
        </div><!-- /input-group -->
    </div><!-- /.col-lg-6 -->
</div><!-- /.row -->
}

但我仍然无法获得@ Model.PossibleAnswers [i]在帖子中的价值我错过了任何东西

1 个答案:

答案 0 :(得分:2)

问题是您发布的数据都不匹配模型上的任何内容。举几个例子:

  1. 当您提取CurrentQuestion时,它已从Model.Questions的上下文中删除,因此生成的字段名称将以CurrentQuestion而不是{{1}开头其中N是该问题的索引。刚刚开始,没有办法填充Questions[N]属性,并且模型上没有Questions属性可以绑定数据。

  2. 当您将CurrentQuestion传递给部分内容时,您甚至会松开此上下文,因此现在部分中的所有字段名称都没有前缀。例如,像CurrentQuestion这样的内容最终只会出现Html.TextBoxFor(m => m.Foo)的名称,这个名称与您的模型结构不匹配。

  3. 然后,在您的部分内容中,您使用的Foo会丢弃更多上下文。当您遍历foreach时,每个字段名称最终都会像Model.PossibleAnswers那样,而不是模型绑定器实际可能使用的内容,如item.IsSelected,其中N是PossibleAnswers[N].IsSelected中项目的索引1}}。

  4. 除此之外,您的复选框甚至没有名称属性。因此,永远不会发布任何价值。周期。

  5. 无论多长时间,您最多都会回复字段名称,模型绑定器无法与模型上的任何内容匹配,最糟糕的是,您根本不会发布任何内容案例。难怪你得到一个空模型。

    在任何时候,您都必须维护属性上下文,以便Razor可以生成模型绑定器可以使用的字段名称。因此,您应该将PossibleAnswers传递给部分,而不是传递CurrentQuestion。在迭代具有可编辑字段的列表时,您需要使用Model.Questions[N]而不是for,以便您可以传递索引属性以向Razor提供所需的上下文:foreach。< / p>