0

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?

2 Answers 2

0

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) {
                            }
                        });
                    }
                });
            }
            });
        });
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Akshay but I wanted to use the list I bought into the CSHTML page via the viewmodel and manipulate the data so I didnt have to do multiple AJAX posts.. I wanted to convert the view model list and use that as the source.
I have looked at this post [link] (stackoverflow.com/questions/14433406/…). I tried pretty much the exact same thing and its erroring on "var students = @Html.Raw(Json.Encode(Model.Students));" specifically Json.Encode... Encode simply doesnt exist. I suspect its as simple as using this sytax but for my it doesnt work on "Encode".
stackoverflow.com/questions/12682128/… If you are facing error in referencing JSON.Encode
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.