HttpPost Action参数为null

时间:2013-08-12 16:37:27

标签: asp.net-mvc asp.net-mvc-4

我的模特是:

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为null
        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,但是当我更改文本框时,文本框文本没有通过参数传递,模型为空,包括QuestionAnswers QuestionAnswerModel }

我有2个模型用于视图。答案和问题。

我有什么问题吗?

1 个答案:

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

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