2

MVC3 カミソリと EF4 を使用して小さな Questionbank アプリケーションを開発しようとしています。ここに私のクエスチョンバンクのカミソリのページがあります:

@using System.Linq

@model MvcApplication1.ViewModels.QuestionBankViewModel
@{
    ViewBag.Title = " Question Bank";

}

    @Html.ValidationSummary(true)


<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />

<script src="../../Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
        @using (Ajax.BeginForm(new AjaxOptions()
  {

      UpdateTargetId = "divToAddQuestion",
      InsertionMode = InsertionMode.InsertAfter,
  }))
  {


<div class="div_question">
    <table class="table_question">
        <tr>
            <td rowspan="3">

            </td>
            <td>
                <span>Question Bank Title</span>
            </td>
            <td>@Html.EditorFor(model => model.QuestionBank.QuestionBankName) @*Question*@
            </td>
            <td>

            </td>
        </tr>
        <tr>
            <td>

            </td>
            <td>
            </td>
            <td>
            </td>
        </tr>


    </table>

        <div class="div_answer">
            <table class="table_answer">
                <tr>
                    <td>
                        <span>Questions()</span>
                    </td>
                    <td>
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    </td>
                    <td>
                        <input type="submit" id="btnAddQuestion" name="ButtonCommand" value="Add Question" class="cancel" />
                    </td>
                    <td></td>
                </tr>
            </table>

        </div>
       <div id="divToAddQuestion">

        </div>
          <div id="divToAddAnswer">
        </div>

</div>
             <div>

        <input type="submit" id="btnSaveQuestionBank" name="ButtonCommand" value="Save" />

    </div>

    }

btnAddQuestion をクリックすると、PartialView _Question が呼び出されます btnAddQuestion をクリックするたびに、partialView ページ _Question が読み込まれます

これが私の部分的なビューです_Question

@using System.Linq

@model MvcApplication1.Models.Question
@{
    ViewBag.Title = " Question";

}

    @Html.ValidationSummary(true)

<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />


<div class="div_question">
    <table class="table_question">
     <tr>

         <td>
                <span>Question Number:</span>
            </td>
             <td >
               @Html.TextBoxFor(model => model.QuestionIndex, new { @class = "tinytextbox" })
            </td>
             <td></td>
        </tr>
        <tr>
            <td>
                <span>Question</span>
            </td>
            <td>@Html.EditorFor(model => model.strQuestion) @*Question*@
            </td>
            <td>
                @Html.ActionLink("Delete this", "Delete", new { id = Model.QuestionIndex }, new { @class = "deletebutton2", title = "Click to delete this Question and its Answers" })
            </td>
        </tr>

    </table>

        <div class="div_answer">
            <table class="table_answer">
                <tr>
                    <td>
                        <span>Answers()</span>
                    </td>
                    <td>
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    </td>
                    <td>
                        <input type="submit" id="btnAddAnswer" name="ButtonCommand" value="Add Answer" class="cancel" />
                    </td>
                </tr>
            </table>

        </div>
      </div>

ここに私のモデルクラスがあります

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace MvcApplication1.Models
    {
        public class QuestionBank 
        {
            public virtual int QuestionBankId { get; set; }
            public virtual string QuestionBankName { get; set; }
            public virtual List<Question> Questions { get; set; }
            public virtual List<Answer> Answers { get; set; }
            public virtual int SubjectTypeId { get; set; }

        }

        public class Question
        {
            public int QuestionId { get; set; }
            public int QuestionIndex { get; set; }
            public string strQuestion { get; set; }
        }

        public class Answer
        {
            public int AnswerId { get; set; }
            public int QuestionId { get; set; }
            public string strAnswer { get; set; }
            public int AnswerIndex { get; set; }
        }
    }

これが私のViewModelです

    using System.Collections.Generic;
using MvcApplication1.Models;

namespace MvcApplication1.ViewModels
{
    public class QuestionBankViewModel
    {
        public QuestionBank QuestionBank { get; set; }
        public IEnumerable<Question> Questions { get; set; }
        public IEnumerable<Answer> Answers { get; set; }
        public string ButtonCommand { get; set; }
        public int QuestionIndex { get; set; }
        public int AnswerIndex { get; set; }
    }

}

をクリックするとbtnAnswer、ロードする必要がありますpartialView _Answer

@using System.Linq
@model MvcApplication1.Models.Answer
@{
    ViewBag.Title = " Answer";

}
@Html.ValidationSummary(true)
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<div class="div_answer">
    <table class="table_answer">
        <tr>
            <td>
                <span>Answer Number:</span>
            </td>
            <td>
                @Html.TextBoxFor(model => model.AnswerIndex, new { @class = "tinytextbox" })
            </td>
            <td>
            </td>
        </tr>
        <tr>
            <td>
                <span>Answer</span>
            </td>
            <td>@Html.EditorFor(model => model.strAnswer) @*Question*@
            </td>
            <td>
            </td>
        </tr>
    </table>
</div>

ここで私は答えを追加することができます。クリックするたびにAdd ans、新しい回答の選択肢が読み込まれます。

ユーザーが質問とそれに対応する回答の追加を終了したら、EF4 コンテキストを使用して質問バンク全体をクリックして保存できます。

ここでの問題は、[保存] ボタンをクリックすると、入力した質問と回答が見つからないことです。

   using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.ViewModels;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        Question qmodel = new Question();
        Answer amodel = new Answer();

        [HttpGet]
        public ActionResult QuestionBank()
        {
            return View();
        }
        [HttpPost]
        public ActionResult QuestionBank(QuestionBankViewModel model)
        {
            switch (model.ButtonCommand)
            {
                case "Add Question":
                    model.QuestionIndex++;
                    qmodel.QuestionIndex = model.QuestionIndex ;
                    return PartialView("_Question", qmodel);
                    break;
                case "Add Answer":
                    model.AnswerIndex++;
                    amodel.AnswerIndex = model.AnswerIndex;
                    return PartialView("_Answer", amodel);
                    break;
                case "Save":
                    this.SaveQuestionBank(model);
                    break;
            }
            return View(model);
        }

        public ActionResult Question()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public void SaveQuestionBank(QuestionBankViewModel model)
        {
            QBContext context = new QBContext();
            foreach (Question question in model.Questions)
            {
                context.Question.Add(question);
            }
            foreach (Answer answer in model.QuestionBank.Answers)
            {
                context.Answer.Add(answer);
            }

            context.QuestionBank.Add(model.QuestionBank);


        }
        public ActionResult About()
        {
            return View();
        }
    }
}

私のユーザーは、質問と回答の選択肢を好きなだけ追加および削除でき、最後に [保存] ボタンをクリックしてすべてを保存できる必要があります。

保存ボタンをクリックすると、コントローラー内で期待IEnumerable<Question> QuestionsIEnumerable<Answer> Answersれますが、常にnullとして取得されます。なぜ、どうすればこれを修正できますか? それとも、私のアプローチに何か問題があると思いますか?

ここに私の完全なソースがそのままありますが、コントローラーへの質問と回答を取得できません。ご意見やご提案をお待ちしております。

4

1 に答える 1

0

私はあなたが投稿したコードを試すことができませんでした.

モデルバインディングを介してコレクションをバインドする場合、name生成される入力要素のプロパティが規則に従う必要があることを確認する必要があります:)

例として..

ドメインモデル

  public class Movie
  {
    public int Id { get; set; }
    public string Name { get; set; }
  }

ビューモデル

  public class AddMoviesModel
  {
    public Movie[] Movies { get; set; }
  }

投稿アクション

[HttpPost]
public ActionResult Index(AddMoviesModel moviesModel)
{
   // save to db?
}

5つの動画を追加できるフォーム

@model MvcBinding.Models.AddMoviesModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm())
{
  for (var i = 0; i < 5; i++)
  {
    <p>
      @Html.EditorFor(m => m.Movies[i])  
    </p>
  }
  <input type="submit" value="Submit"/>
}

ここで注目すべき重要なことは、5 つのムービーを追加するための入力要素を生成する方法です。ビュー ソースが表示されている場合、入力要素の名前はMovies[0].x、Movies[1].x .. のようになります (注意Moviesは のプロパティ名ですAddMoviesModel) 。

<input type="text" name="Movies[0].Id" />
<input type="text" name="Movies[0].Name" />

<input type="text" name="Movies[1].Id" />
<input type="text" name="Movies[1].Name" />

...

ビュー ソースを確認し、入力要素の名前がコレクションのモデル バインドを行うための規則に従っていることを確認してください。

アップデート:

私はコードを調べました.. うーん..

問題は、既に親フォームがあり、[質問の追加] ボタンをクリックするたびに新しい子フォームを追加していることです。メインフォームを送信しようとすると、子フォームの質問がサーバーに投稿されないため、バインドされません:(

各質問と回答のペアを HTML 形式でラップする必要があるのはなぜですか?

実際のところ、AJAX 呼び出しを行うためだけに HTML フォームは必要ありません。

(送信ではなく) 通常のボタンに [質問追加] と [回答の追加] を変更する必要があり、 JavaScript をこれらのボタンのクリック イベントにフックして、サーバー呼び出しを行って部分ビューを取得するか、これらのボタンを Ajax に置き換えることもできます。 .ActionLinks. 実装方法を今すぐ変更する必要があります

于 2012-05-26T16:51:06.337 に答える