简体   繁体   English

使用从JavaScript /淘汰列表下拉列表中选择的值填充MVC3视图模型?

[英]Populating MVC3 view model with a selected value from a JavaScript/Knockout dropdown?

I'm looking for advice on how to populate the viewmodel passed to the view after a list is retrieved and an item selected in a dropdown list. 我正在寻找有关如何在检索列表并在下拉列表中选择项目后填充传递给视图的viewmodel的建议。 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. 请注意,我还有一个用于Ajax / Knockout客户端代码的客户端视图模型,但这不是我要填充的视图模型。 I may have to map from one view model to the other but I'm not sure if that is the correct solution. 我可能必须从一个视图模型映射到另一个视图模型,但是我不确定这是否是正确的解决方案。

View - Form 查看-表格

In my form I am using Knockout and JavaScript for my dropdowns. 在我的表单中,我正在使用下拉菜单和JavaScript。 How can I populate the view model m.VMResidencyWTCS.ScCountyCd field with the county code value that is selected? 如何用选定的县代码值填充视图模型m.VMResidencyWTCS.ScCountyCd字段? Is it possible to also capture the desription? 是否有可能也捕获到目标? If so, how would this be done as well? 如果是这样,该如何做?

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

View - JavaScript 查看-JavaScript

This is my script for calling back to the controller for the county dropdown list. 这是我的脚本,用于回调县下拉列表的控制器。 Note that the county dropdown is populated when a state is selected in another dropdown. 请注意,在另一个下拉列表中选择州时,将填充县下拉列表。

<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. 请注意,我还有一个用于Ajax / Knockout客户端代码的客户端视图模型,但这不是我要填充的视图模型。 I may have to map from one view model to the other but I'm not sure if that is the correct solution. 我可能必须从一个视图模型映射到另一个视图模型,但是我不确定这是否是正确的解决方案。

Ok, there are some yellow flags going up. 好的,有一些黄旗在上升。

Let me restate your question to verify my understanding: you've got a view model with an observable bound to a <select> box. 让我重新陈述您的问题,以验证我的理解:您已经有了一个视图模型,该模型具有可观察的绑定到<select>框的视图。 Let's pretend it's vm1.mySelection. 假设它是vm1.mySelection。

You have a 2nd view model, and you want to store vm1.mySelection inside vm2.mySelection. 您具有第二视图模型,并且想要将vm1.mySelection存储在vm2.mySelection中。

Is that correct? 那是对的吗?

If so, my first thought is, "You're probably doing it wrong." 如果是这样,我首先想到的是:“您可能做错了。” Please explain why you think you need this, and we'll tell you whether there's a better way. 请说明为什么您认为自己需要这个,我们会告诉您是否有更好的方法。

Secondly, if you truly do need this, you could manually subscribe to vm1.mySelection inside vm2, then set the value accordingly in vm2. 其次,如果您确实需要这样做,则可以在vm2中手动订阅vm1.mySelection,然后在vm2中相应地设置值。 But again, this feels hackish, and you might be doing it wrong. 但是,这又再次让人感到骇人听闻,您可能做错了。

My design may be not be the best. 我的设计可能不是最好的。 I have a view model being passed to the view from the server as defined in the view statement ( @model Apps.Model.ViewModels.AVMApplicationInfo ). 我有一个视图模型,该视图模型是按照视图声明( @model Apps.Model.ViewModels.AVMApplicationInfo )中的定义从服务器传递给视图的。 I use this extensively in the view "form" to capture information to build a web service call. 我在“表单”视图中广泛使用此功能来捕获信息以构建Web服务调用。

I needed to add some cascading dropdowns to get filtered information. 我需要添加一些级联下拉菜单以获取过滤信息。 To do this I added the knockout code and the clientside view model (var residencyViewModel = new residency(); ko.applyBindings(residencyViewModel); ). 为此,我添加了删除代码和客户端视图模型(varresidentncyViewModel = newresidentncy(); ko.applyBindings(residencyViewModel);)。 This is used to call back to the controller via ajax to get the dropdown values. 这用于通过ajax回调到控制器以获取下拉值。 Once the dropdown value has been selected I would like to store the selection in the Apps.Model.ViewModels.AVMApplicationInfo view model. 选择下拉值后,我想将选择内容存储在Apps.Model.ViewModels.AVMApplicationInfo视图模型中。 I'm not sure if I need the clientside view model but I'm not sure how else to code this. 我不确定是否需要客户端视图模型,但不确定如何编写此代码。

The selected value would also be used for subsequent cascading dropdowns (as another filter value). 所选值还将用于后续的级联下拉列表(作为另一个过滤器值)。 Some dropdowns use the selected values from multiple dropdowns selected earlier in the form; 一些下拉菜单使用从表单中较早选择的多个下拉菜单中选择的值; ie, they have more than one filter such as: country, state, county, municipality. 也就是说,它们具有多个过滤器,例如:国家,州,县,市。 This is due to the table structure which can't be changed. 这是由于表结构无法更改。 Ultimately though when all the selections have been made the Apps.Model.ViewModels.AVMApplicationInfo view model must be populated with all the selections to pass the values back to the server for the web service call. 最终,尽管在完成所有选择之后,必须使用所有选择填充Apps.Model.ViewModels.AVMApplicationInfo视图模型,才能将值传递回服务器以进行Web服务调用。

Does that make sense? 那有意义吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM