0

我的模型是:

public class Answer
{


public string AnswerText { get; set; }

public static List<Answer> GetAnswers(string[] answers)
{
    List<Answer> _answers = new List<Answer>();

    foreach (string _answer in answers)
    {
        Answer _answer1 = new Answer()
        {
            AnswerText = _answer
        };

        _answers.Add(_answer1);
    }

    return _answers;
}
}

public class Question
{
    [Required]
    public string QuestionText { get; set; }
}

public class QuestionAnswerModel
{
    public List<Answer> Answers { get; set; }
    [Required]
    public Question Question { get; set; }

我的控制器是:

        [HttpPost]

//通过更改视图的文本框进行发布时,此_model为空

        public ActionResult A(QuestionAnswerModel _model)
        {

           QuestionAnswerModel _questionanswerModel = new QuestionAnswerModel();
//            _questionanswerModel.Answers = Answer.GetAnswers(_response.GetAnswerResult);

            _questionanswerModel.Question = new Question();

            return View(_questionanswerModel);
        }

        [HttpGet]
        public ActionResult A(string question)
        {

            QuestionAnswerModel _questionanswerModel = new QuestionAnswerModel();
//            _questionanswerModel.Answers = Answer.GetAnswers(_response.GetAnswerResult);

            _questionanswerModel.Question = new Question() {
                QuestionText = question
            };

            return View(_questionanswerModel);
        }

我的看法是:

@model ProjectnameSample.Models.QuestionAnswerModel

@{
    ViewBag.Title = "A";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>A</h2>

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

    <fieldset>
        <legend>QuestionAnswerModel</legend>
        @Html.TextBoxFor(m => m.Question.QuestionText)
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

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

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

我有用于操作的 HttpPost 和 HttpGet,但是当我更改文本框时,文本框文本没有通过参数传递,并且模型为空,包括QuestionAnswersQuestionAnswerModel

我有 2 个模型供查看。答案和问题。

有什么我做错了吗?

4

1 回答 1

0

在我看来,这应该有效:

[HttpPost]
public ActionResult A(QuestionAnswerModel _model)
        {
         var question = _model.Question;
         var answers = db.Answers.Where(g=>g.questionID == question.ID).ToList() // Or question.Answers.ToList() or other selector

 var model = new QuestionAnswerModel
{
Answers = answers,
Question = question   
};
            return View(model);
        }

你得到空值,因为试图获得新实例Question的属性。_questionanswerModel相反,您需要_model从表单中获取它。

于 2013-08-12T17:10:14.167 回答