模型绑定回发

时间:2013-06-21 07:33:24

标签: c# asp.net-mvc asp.net-mvc-4 model-binding

我有2个像这样的方法

public ViewResult Detail(int Id)
    {
        if (Id != null)
        {
            Context context = new Context();
            Poll PollDetail = context.Polls.FirstOrDefault(x => x.Id == Id);
            PollDetail.Answers = new List<Answer>();
            Context Context = new Context();
            PollDetail.Answers = Context.Answers.Where(x => x.PollId == PollDetail.Id).ToList();
            return View("../Home/Index", PollDetail);
        }
        RedirectToAction("Index", "Home");
    }

[HttpPost]
    public ActionResult PollVote(Poll CurrentPoll)
    {
        Context Context = new Context();
        foreach (Answer item in CurrentPoll.Answers)
        {
            item.VoteCount = item.VoteCount + 1;
        }

        return View();
    }

有cshtml。所以本节没有问题。

<div class="container">
   @Html.Partial("Header")
    @if (Model == null)
    {
        @Html.Partial("CreatePoll")
    }
    else
    {
        using (@Html.BeginForm("PollVote", "Poll", FormMethod.Post, new { id = "PollVoteForm" }))
        {
            <div class="row-fluid">
                <div class="span12 pageHeader">
                    <h2>SORU:</h2>
                    @Html.LabelFor(m => m.Question, Model.Question, new { @class = "question-input", @id = "question" })
                </div>
            </div>
            <div id="answers" class="row-fluid">

               @foreach (Answer answer in Model.Answers)
                {
                    <p class="external">

                        @Html.RadioButtonFor(m => answer.Content, answer.Content, new { @name = "rb", @class = "answer-radio", @id = "answer-" + answer.Counter, @checked = "false" })
                        @Html.Label(answer.Content, new { @for = "answer-" + answer.Counter })
                        @Html.HiddenFor(m => answer.Content)

                    </p>
                }

            </div>

            <div class="row-fluid">
                <div class="span6"></div>
                <div class="span5">
                    <input type="submit" value="Oyla" class="btnPS" />
                </div>
            </div>
        }
    }


   <div class="footer"></div>
</div>

民意调查模型完美绑定。但我无法回复任何数据。当我在index.cshtml中提交表单时。 CurrentPoll模型为空。我该如何解决?

1 个答案:

答案 0 :(得分:1)

Asp.Net MVC需要您的模型上的属性才能进行模型绑定。因此,请检查您的模型并确保所有成员都作为属性公开。

例如:您将模型更改为如下所示。

public class Poll 
{
    public Answer Answers { get; set; }
}