如何通过List< model>到MVC 4中的控制器 [英] How to pass List<model> to controller in MVC 4

查看:58
本文介绍了如何通过List< model>到MVC 4中的控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个模型:如下所示的问答,我想将List模型发送到View,并且在提交表单时,我将List模型提交到控制器,但是在Action UpdateQuestion中,a只能获取问题列表,但是答案清单不是.您能解释一下并告诉我如何在提交表单时获得每个问题的列表答案吗?

I have 2 model : Question and Answer such as below, I want to send a List model to View, and when submit form, i submit List model to controller, but in Action UpdateQuestion a can only get the list of question but the list of answer was not. Can you explain and show me how to get list answer of each question when i submit form

public class Question
    {
        [Key]
        public int Id { get; set; }

        [ForeignKey("QuestionType")]
        public int QuestionTypeId { get; set; }
        public virtual QuestionType QuestionType { get; set; }

        [ForeignKey("Field")]
        public int FieldId { get; set; }
        public virtual Field Field { get; set; }

        public string Brief { get; set; }

        public bool IsGroup { get; set; }

        [ForeignKey("QuestionGroup")]
        public int? QuestionGroupId { get; set; }
        public virtual QuestionGroup QuestionGroup { get; set; }

        public int Priority { get; set; }

        public int Order { get; set; }

        public virtual ICollection<Answer> Answers { get; set; }
    }

和:

public class Answer
    {
        [Key]
        public Int32 Id { get; set; }

        [Column(TypeName = "ntext")]
        [MaxLength]
        public string Content { get; set; }      

        [ForeignKey("Question")]      
        public int QuestionId { get; set; }
        public virtual Question Question { get; set; }      

        public float Mark { get; set; }

        public int Priority { get; set; }    
    }

我具有控制器索引,可以将问题列表传递给视图:

I have controller Index to passing a list of Question to View:

public ActionResult Index()
{
     ApplicationDbContext db = new ApplicationDbContext();
            var listQuestion = db.Questions.ToList();
return View(listQuestion);
}

[HttpPost]

[HttpPost]

        public ActionResult UpdateQuestion(string submit, List<Question> Questions)
        {
        ...

        return RedirectToAction("Index");
}

而且在视野中:

@model List<Question>
@{
    int i = 0;
    int j = 0;
}
@using (Html.BeginForm("UpdateQuestion", "TestRoom")) 
{ 
     <ul>
         @foreach(var question in Model)//Question
         {                                
              <li>
              @Html.Hidden("Questions["+i+"].Id", question.Id)
              @{i++;}
              @Html.Raw(question.Brief)
              <ul>
                   @foreach (var answers in question.Answers)
                   {                                            
                        <li>@Html.RadioButton("Questions["+i+"]_Answers["+j+"]",answers.Id)                                                
                                                @Html.Raw(answers.Content)

                                                @{j++;}
                                            </li>
                                        }
                                        @{j = 0;}
                                    </ul>
                                </li>
                            }

                        </ul>
                        <div class="aq-button-panel">
                            <button type="submit" value="Finish" name="submit"><i class="icon-pencil"></i>Submit</button>
                            <button type="submit" value="Back" name="submit">Go Next <i class="icon-arrow-left"></i></button>
                            <button type="submit" value="Next" name="submit">Go Back <i class="icon-arrow-right"></i></button>                        
                        </div>
                    }

推荐答案

您的代码存在多个问题.首先,您不能将单选按钮绑定到复杂的对象(在您的情况下为Answer,因为单选按钮组仅回发单个值(在您的情况下为所选Answerid值).生成单选按钮组,这些单选按钮组将尝试将选择的答案仅绑定到没有任何意义的第一个答案(您每次将j的值设置为0).模型需要一个属性来绑定(例如) int SelectedAnswer.

There are multiple issues with you code. First you cannot bind a radio button to a complex object (in your case Answer because a radio button group only posts back a single value (in your case the id value of the selected Answer). Next you loops are generating radio buttons groups that would be attempting to bind the selected answer to only the first answer which makes no sense (your setting the value of j to 0 each time). Your model needs a property to bind to (say) int SelectedAnswer.

首先创建表示要在视图中显示/编辑的视图模型(根据需要添加显示和验证属性)

Start by creating view models that represent what you want to display/edit in your view (add display and validation attributes as required)

public class AnswerVM
{
  public int ID { get; set; }
  public string Content { get; set; }
}
public class QuestionVM
{
  public int ID { get; set; }
  public string Brief { get; set; }
  public int SelectedAnswer { get; set; }
  public IEnumerable<AnswerVM> PossibleAnswers { get; set; }
}

在get方法中,获取数据模型并映射,然后映射到视图模型,然后将IEnumerable<QuestionVM>返回到视图.

In your get method, get your data models and map then to the view models and return IEnumerable<QuestionVM> to the view.

接下来,为typeof QuestionVM(/Views/Shared/EditorTemplates/QuestionVM.cshtml)

Next create an EditorTemplate for typeof QuestionVM (/Views/Shared/EditorTemplates/QuestionVM.cshtml)

@model QuestionVM
<li>
  @Html.HiddenFor(m => m.ID)
  @Html.DisplayFor(m => m.Brief)
  <ul>
    @foreach(var answer in Model.PossibleAnswers)
    {
      <li>
        <label>
          @Html.RadioButtonFor(m => m.SelectedAnswer, answer.ID, new { id = "" })
          <span>@answer.Content</span>
        </label>
      </li>
    }
  </ul>
</li>

并在主视图中

@model IEnumerable<QuestionVM>
....
@Html.BeginForm(...))
{
  <ul>
    @Html.EditorFor(m => m) // this will generate the correct html for each question in the collection
  </ul>
  <div class="aq-button-panel">
    <button type="submit" ... />
    ...
  </div>
}

并将POST方法更改为

and change the POST method to

[HttpPost]
public ActionResult UpdateQuestion(string submit, IEnumerable<QuestionVM> model)

模型现在包含每个问题的ID和每个问题的选定答案的ID.

The model now contains the ID of each question and the ID of the selected answer for each question.

请注意,如果由于ModelState无效而需要返回视图,则需要重新填充每个问题的PossibleAnswers属性(您不会为每个Answer中每个Answer的每个属性生成表单控件c13>-也不应),这样,当您提交表单时,PossibleAnswers属性将是一个空集合)

Note that if you need to return the view because ModelState is invalid, you will need to repopulate the PossibleAnswers property of each question (your not generating a form control for each property of each Answer in each Question - and nor should you) so the PossibleAnswers property will be an empty collection when you submit the form)

这篇关于如何通过List&lt; model&gt;到MVC 4中的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆