gpt4 book ai didi

javascript - 使用 JavaScript/Knockout 下拉列表中选定的值填充 MVC3 View 模型?

转载 作者:行者123 更新时间:2023-11-28 10:05:08 25 4
gpt4 key购买 nike

我正在寻找有关如何在检索列表并在下拉列表中选择项目后填充传递到 View 的 View 模型的建议。请注意,我还有一个用于 Ajax/Knockout 客户端代码的客户端 View 模型,但这不是我要填充的 View 模型。我可能必须从一个 View 模型映射到另一个 View 模型,但我不确定这是否是正确的解决方案。

查看 - 表单

在我的表单中,我使用 Knockout 和 JavaScript 作为下拉菜单。如何使用所选的县代码值填充 View 模型 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

这是我的脚本,用于回调县下拉列表的 Controller 。请注意,当在另一个下拉列表中选择一个州时,就会填充县下拉列表。

<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>

Controller

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);
}

最佳答案

Note that I also have a client side viewmodel that is used for the Ajax/Knockout client code but this is not the view model that I am trying to populate. I may have to map from one view model to the other but I'm not sure if that is the correct solution.

好的,有一些黄旗升起。

让我重申一下你的问题来验证我的理解:你有一个 View 模型,它的可观察对象绑定(bind)到

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com