リストが取得された後にビューに渡されたビューモデルとドロップダウンリストで選択された項目を取り込む方法に関するアドバイスを探しています。クライアント側のビューモデルもAjax/Knockoutクライアントコードに使用されていますが、これは表示しようとしているビューモデルではありません。あるビューモデルから別のビューモデルにマップする必要があるかもしれませんが、それが正しい解決策であるかどうかはわかりません。MVC3ビューモデルにJavaScript/Knockoutドロップダウンから選択した値を入力しますか?
ビュー - フォーム
私の形で私は私のドロップダウンのためのノックアウトとJavaScriptを使用しています。ビューモデルm.VMResidencyWTCS.ScCountyCdフィールドに、選択された郡コード値を入力するにはどうすればよいですか?デシスクリングをキャプチャすることも可能ですか?もしそうなら、これはどのようにして行われますか?
@model Apps.Model.ViewModels.AVMApplicationInfo
...
@using (Html.BeginForm("ApplicationDetails", "PersonalInfo"))
{
<fieldset>
<div class="appl-step">
...
<div class="editor-label">
<span class="error">*</span>@Html.LabelFor(m => m.VMResidencyWTCS.ScCountyCd)
</div>
<div class="editor-field">
<select id='counties'
data-bind='
options: selectedResidencyState() ? counties : null,
optionsValue : "CountyCd",
optionsText: "CountyDescr",
optionsCaption: "[Please select a county]",
value: selectedCounty,
visible: (counties() && counties().length > 0)'>
</select>
<span data-bind='
template: {name: "noInfoTemplate"},
visible: !(counties() && counties().length > 0)'>
</span>
</div>
ビュー - JavaScriptの
これは、郡のドロップダウンリストのためのコントローラに戻って呼び出すための私のスクリプトです。他のドロップダウンで状態が選択されると、郡のドロップダウンが設定されます。
<script type='text/javascript'>
$(document).ready(function() {
var residency = function() {
this.selectedResidencyState = ko.observable();
this.selectedCounty = ko.observable();
...
this.states = ko.observableArray();
this.counties = ko.observableArray();
...
this.selectedResidencyState.subscribe(function (stateCd) {
this.selectedCounty(undefined);
this.counties(undefined);
if (stateCd != null) {
$.ajax({
url: '@Url.Action("GetCounties", "PersonalInfo")',
data: { stateCd: stateCd },
type: 'GET',
success: function (data) {
residencyViewModel.counties(data);
}
});
}
} .bind(this));
};
var residencyViewModel = new residency();
ko.applyBindings(residencyViewModel);
//Load the states
$.ajax({
url: '@Url.Action("GetResidencyStates", "PersonalInfo")',
type: 'GET',
success: function (data) {
residencyViewModel.states(data);
}
});
});
</script>
コントローラ
public class PersonalInfoController : Controller
{
…
[HttpGet]
public virtual ActionResult GetCounties(string stateCd)
{
var counties =
(
from county in this._countyRepository.All
where (county.CountryCd == "USA" && county.ResidencyStateCd == stateCd)
select new
{
CountyCd = county.CountyCd,
CountyDescr = county.CountyDescr,
StateCd = county.ResidencyStateCd,
CountryCd = county.CountryCd // Added for populating model ?Needed?
}
).ToList();
return Json(counties, JsonRequestBehavior.AllowGet);
}
私は少しあなたの質問に混乱しています。郡のコードをノックアウトビューモデルにする方法を尋ねていますか? – Tyrsius