0

I am using the jQuery auto complete feature, in which the value are to be stored in a java script array. I have created a function that gives a list with objects that contain user_id and user_name. How to convert it into an array.

public class DocModel
{
    [Required]
    public String dr_name { get; set; }
    [Required]
    public int dr_id { get; set; }
    public List<DocModel> GetUser()
    {
        SqlDataReader sdr = DataAccess.DataAccess.getAllDoctorNames();
        List<AECS1.Models.DocModel> DocList = new List<Models.DocModel>();
        Models.DocModel Doc;
        if (sdr.HasRows)
        {
            while (sdr.Read())
            {
                Doc = new Models.DocModel();
                Doc.dr_id = (int)sdr["dr_id"];
                Doc.dr_name = (string)sdr["dr_name"];
                DocList.Add(Doc);
            }
        }
        return DocList;

    }
}

This is the view page :

$(function () {
    var docdata = [];


    $("#tags").autocomplete({
        source: docdata
    });
});

How to fill up this docdata array ?

1
  • you could return a JSON from DocList, actually you must since the data is going to be used in the autocomplete Commented Mar 8, 2014 at 15:50

2 Answers 2

1

Add a method to your model called ToJSON & use a JavaScript converter - either the one built in or even better, the JSON.net one & have this method return the json encoded string representing your array.

<script>
    var docdata = @Model.ToJson();
</script>

If you don't like having the method in your model, do the JSON conversion as you populate your model.

Sign up to request clarification or add additional context in comments.

Comments

0

Pass DocModels to view as model.

@model IEnumerable<DocModel>

And then

<script>
    var docdata = [
    @foreach(var item in Model)
    {
        @: '@item.dr_name',
    }
    ];
</script>

2 Comments

This is problematic. You're only html escaping, not JavaScript escaping. Different rules apply.
Yes. Am getting the desired output with this. But how would i set values to the list elements ?

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.