简体   繁体   中英

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:

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.

I have tried various javascript options indicated from other questions on this forum like here .

I would like to have a javascript variable that represents the list and I have tried just setting:

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:

        var test =[];

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

I have also tried using "push" and ".Encode".

I would like to know how to assign this list of strings and state object to a javascript variable?

Use Ajax Call to achieve Auto-complete functionality

  $(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. 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("");
                }
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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