は、何のポストバック動作はありません。フォームを投稿することはできますが、アクションメソッドでは、選択した値(投稿値)を読み込み、テキストボックスの値を読み込んでページを再描画することができます。これは完全な書式転記です。しかし、ajaxを使ってこれを行うより良い方法があるので、ユーザーは完全なページのリロードを経験しません。あなたは何
は、ユーザーがドロップダウンを変更すると、選択した項目の値を取得し、あなたが入力フィールドに表示し、それらを設定するデータを取得するために、サーバーへの呼び出しを行い、です。
ページのビューモデルを作成します。
public class CreateViewModel
{
public int Width { set; get; }
public int Height{ set; get; }
public List<SelectListItem> Widgets{ set; get; }
public int? SelectedWidget { set; get; }
}
は今すぐGETアクションで、私たちは、このオブジェクトを作成するウィジェットのプロパティを初期化し、ビューに
public ActionResult Create()
{
var vm=new CreateViewModel();
//Hard coded for demo. You may replace with data form db.
vm.Widgets = new List<SelectListItem>
{
new SelectListItem {Value = "1", Text = "Weather"},
new SelectListItem {Value = "2", Text = "Messages"}
};
return View(vm);
}
を送信し、あなたを強くCreateViewModel
に型付けされたビューを作成します。
@model ReplaceWithYourNamespaceHere.CreateViewModel
@using(Html.BeginForm())
{
@Html.DropDownListFor(s => s.SelectedWidget, Model.Widgets, "Select");
<div id = "editablePane" >
@Html.TextBoxFor(s =>s. Width,new { @class ="myEditable", disabled="disabled"})
@Html.TextBoxFor(s =>s. Height,new { @class ="myEditable", disabled="disabled"})
</div>
}
上記のコードでは、SELECT要素のhtmlマークアップとWidthとHeightの2つの入力テキストフィールドが表示されます。
ここでは、SELECT要素のchange
イベントをリッスンし、選択した項目値を読み込むjQueryコードがあります。サーバーにajaxコールを送信して選択したウィジェットの高さと幅。
<script type="text/javascript">
$(function(){
$("#SelectedWidget").change(function() {
var t = $(this).val();
if (t !== "") {
$.post("@Url.Action("GetDefault", "Home")?val=" + t, function(res) {
if (res.Success === "true") {
//enable the text boxes and set the value
$("#Width").prop('disabled', false).val(res.Data.Width);
$("#Height").prop('disabled', false).val(res.Data.Height);
} else {
alert("Error getting data!");
}
});
} else {
//Let's clear the values and disable :)
$("input.editableItems").val('').prop('disabled', true);
}
});
});
</script>
我々はAJAX呼び出しを処理するためにHomeController
内GetDetault
と呼ばれるアクションメソッドを持っていることを確認する必要があります。
[HttpPost]
public ActionResult GetDefault(int? val)
{
if (val != null)
{
//Values are hard coded for demo. you may replae with values
// coming from your db/service based on the passed in value (val.Value)
return Json(new { Success="true",Data = new { Width = 234, Height = 345}});
}
return Json(new { Success = "false" });
}
Jsonデータを返すControllerアクションを作成し、そのアクションへのドロップダウンのajax call onchangeを作成します。 ajaxレスポンス(json)では、値を取得し、それらの値をフィールドに設定してjsonレスポンスを形成します。 –
同じ結果を得るためにアクションメソッドにPOSTすることはできますが、[ここに例があります](http://stackoverflow.com/questions/5497524/easiest-way-to-create-a-cascade-dropdown-in-asp -net-mvc-3-with-c-sharp)を使用してください。 – markpsmith
あなたはビュー自体でそれをやりたいのですか、あるいは実際にバックエンドから何かを照会する必要がありますか? – Theunis