简体   繁体   English

MVC6将viewmodel列表属性分配给javascript变量

[英]MVC6 Assign a viewmodel list property to a javascript variable

I have a viewmodel with the following property: 我有一个具有以下属性的视图模型:

public class CompanyDetailsViewModel
{

    [Required(ErrorMessage = "A Company Name is required")]
    [Display(Name = "Company Name:")]
    [StringLength(100)]
    public string CompanyName { get; set; }

   ...

    public IList<SuburbAndPostcode> SuburbAndPostcodesList { get; set; }
}

The list was created from this POCO class: 该列表是从此POCO类创建的:

public class SuburbAndPostcode
{
    [Key]
    public int SuburbsAndPostcodesId { get; set; }
    public string Suburb { get; set; }
    public string PostCode { get; set; }
    public State State { get; set; }

}

This is the state object: 这是状态对象:

 public class State
{
    [Key]
    public int StateId { get; set; }
    public string ShortName { get; set; }
    public string Name { get; set; }

    public virtual ICollection<CompanyDetail> CompanyDetails { get; set; }
}

I am trying to create a variable with the suburb and postcode properties as a list that I can use for an autocomplete function however I cant seem to assign the Model.SuburbsAndPostCodesList to a variable. 我试图创建一个具有郊区和邮政编码属性的变量作为列表,可以将其用于自动完成功能,但是我似乎无法将Model.SuburbsAndPostCodesList分配给变量。

I have tried various javascript options indicated from other questions on this forum like here . 我试图从这个论坛上跟其他的问题表示的各种JavaScript选项这里

I would like to have a javascript variable that represents the list and I have tried just setting: 我想有一个代表列表的javascript变量,我已经尝试过设置:

var suburbs = @Model.SuburbAndPostcodesList 

I've tried using json and I have tried looping through the Model but get an error saying that the variable "test" is out of context: 我已经尝试过使用json并尝试遍历模型,但是收到一条错误消息,指出变量“ test”不在上下文中:

        var test =[];

        @for (int i = 0; i < Model.SuburbAndPostcodesList.Count; i++)
        {
            test[i]=...
        }

I have also tried using "push" and ".Encode". 我也尝试过使用“ push”和“ .Encode”。

I would like to know how to assign this list of strings and state object to a javascript variable? 我想知道如何将此字符串和状态对象列表分配给javascript变量?

Use Ajax Call to achieve Auto-complete functionality 使用Ajax Call实现自动完成功能

  $(document).ready(function () {
            $("#txtPostcodes").keyup(function () {

                //AutoComplete the Results
                $("#txtPostcodes").autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            url: "../ControllerName/ActionName",
                            data: "{'input':'" + document.getElementById('txtPostcodes').value + "'}",
                            dataType: "json",
                            success: function (data) {
                                if (data != null) {
                                    var suburbs = data;                              
                                }
                            },
                            error: function (result) {
                            }
                        });
                    }
                });
            }
            });
        });

In the end I simply equated the various members of the viewmodel list and build up a javascript multi dimensional array for the autocomplete function. 最后,我简单地将viewmodel列表的各个成员等同起来,并为自动完成功能建立了一个javascript多维数组。 Here it is: 这里是:

 var suburbs = [
   @for (var i = 0; i < Model.SuburbAndPostcodesList.Count; i++) {
           <text>{
       id: "@Model.SuburbAndPostcodesList[i].SuburbsAndPostcodesId",
       suburb: "@Model.SuburbAndPostcodesList[i].Suburb",
       postCode: "@Model.SuburbAndPostcodesList[i].PostCode",
       state: "@Model.SuburbAndPostcodesList[i].State.ShortName"
   }@(i == Model.SuburbAndPostcodesList.Count - 1 ? "" : ",")</text>
       }
        ];

        $("#Suburb").autocomplete({
            source: function (req, responseFn) {
                var re = $.ui.autocomplete.escapeRegex(req.term);
                var matcher = new RegExp("^" + re, "i");
                var a = $.grep(suburbs, function (item, index) {
                    return matcher.test(item.suburb);
                });
                a = $.map(a, function (x) {
                    return {
                        label: x.suburb + " - " + x.postCode,
                        value: x.suburb,
                        suburbDetails: x
                    };
                });
                responseFn(a);
            },
            select: function (value, data) {
                if (typeof data == "undefined") {
                } else {
                    $("#Postcode").val(data.item.suburbDetails.postCode);
                }
            },
            change: function (event, ui) {
                if (!ui.item) {
                    $("#Suburb").val("");
                    $("#Postcode").val("");
                }
            }
        });

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

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