0

「質問」オブジェクトのコントローラーがあります。これらの質問が「MultipleChoice」タイプの場合、「MultipleChoiceOption」オブジェクトのコレクションを質問に追加できるようにしたいと考えています...これまでのところ、とても良いです。

私が抱えている問題は、質問を編集し、そのタイプを MultipleChoice に変更してからオプションを追加するときに、[質問の編集] ビューに戻って編集した質問をコミットする必要があることです。そうしないと、Question.Type の変更が失われます。明らかにこれは少し面倒なので、ドロップダウン リストの値が変更されるたびに、QuestionController で関連するメソッドを起動するメソッドを接続したいと考えています。

質問の編集ビューには次のものがあります。

@Html.DropDownListFor(model => model.Type, Helper.GetSelectList(), new { id = "QuestionTypeDropDown", onchange = "OnChange();" })

<script type="text/javascript">


function OnChange(text) {
    ...do something here

        }

    }
</script>

私の質問コントローラのこのメソッド:

[HttpPost]
    public ActionResult QuestionTypeEdited(Question question)
    {
        if (ModelState.IsValid)
        {
            SaveQuestion(question, false);
            return RedirectToAction("Edit", "Question", new { id = question.OwningPulseId });
        }
        return View(question);
    }

しかし、それらを接続する方法がわかりません。オンラインで見つけたAjaxを使用して1つの方法を試しましたが、これによりjsがまったく起動しなくなりました(おそらくAjaxを持っていませんか?申し訳ありませんが、Ajaxについて何も知らないので、それはばかげた声明かもしれません!)。「単純な」Javascriptを使用することは可能ですか?

コントローラーを明示的に指定する必要がある場合は、知っている場合はその方法を必ず記載してください:-)

乾杯

4

2 に答える 2

1

これはあなたができることの非常に基本的な例です。(テストされていません)

javascript:

// wire up your change event unobtrusively with jQuery
$("#Type").change(function() {
  // find the form that the select belongs to and serialize it
  var question = $(this).closest("form").serialize();
  // POST the form data to your controller
  $.post("Question/QuestionTypeEdited", question, function(data) {
      // this function executes when the POST completes
      // if data has a RedirectUrl, redirect
      if (data.RedirectUrl)
      {
         window.location = data.RedirectUrl;
      }
      else
      {
         // display any errors - I'm using alert because its very simple, you'll probably want to use a div
         alert(data.Errors);
      }
  });
});

アクションは次のとおりです。

[HttpPost]
public ActionResult QuestionTypeEdited(Question question)
{
    if (ModelState.IsValid)
    {
        SaveQuestion(question, false);

        // return a JSON result with a redirect url
        return Json(new {RedirectUrl = "Edit/Question/"+question.OwningPulseId});
    }

    // return a JSON result with the errors
    return Json(new {Errors = ModelState.Errors});
}

参照:

于 2012-10-12T13:00:27.567 に答える
0

ddl が変更されたときにコントローラーへのポストバックだけを取得したい場合は、次のようにするだけです。

<script type="text/javascript">

function OnChange() {
    document.forms[0].submit();

    }
</script>

あなたがフォーム内にいると仮定します:

@using (Html.BeginForm())

DropDownListFor から [HttpPost] コントローラーへの値を取得します。

于 2012-10-12T13:13:23.703 に答える