2013-06-21 33 views
0

我有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模型为空。我该如何解决它?

+0

你可以显示提交给'PollVote'的表单的代码吗? – Andrei

+0

您能显示index.cshtml的代码 – Longball27

+2

请在index.cshtml中显示您的代码和Poll类的定义 – ojlovecd

回答

1

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

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

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

我做了这样的事情 public IList Answers {get;组; } – OzanWt

+0

感谢您的回答。我在一个班级中忘了get/set属性,并且试图解决这个问题让我开了2个小时。 – 1c1cle