简体   繁体   中英

Typeahead/bootstrap-tagsinput with MVC controller not working

I want to implement tag functionality in asp.net MVC I have took reference from " Bootstrap Tags ". Below is the sample code which is working properly for me. As in URL I have passed static JSON file path.

    var citynames = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
        //url: 'http://localhost:20182/Home/JsonData',
        url: '../Content/citynames.json',

        filter: function (list) {
            return $.map(list, function (cityname) {
                return { name: cityname };
            });
        }
    }
});
citynames.initialize();

var elt = $('.example_typeahead > > input');

elt.tagsinput({
    typeaheadjs: {
        name: 'cityname',
        displayKey: 'name',
        valueKey: 'name',
        source: citynames.ttAdapter()
    }});

But as soon as I changed in URL with my controller it won't work as below. I have just changed url with full url and with controller and action.

    prefetch: {
    url: 'http://localhost:20182/Home/JsonData',
    //url: '../Content/citynames.json',

    filter: function (list) {
        return $.map(list, function (cityname) {
            return { name: cityname };
        });
    }
}

My Action is as below

    public JsonResult JsonData()
    {
        var data = System.IO.File.ReadAllText(Server.MapPath(@"~/Content/citynames.json"));
        return Json(data, JsonRequestBehavior.AllowGet);

    }

Please let me know how could I pass json data using controller and action instead using static data from json file URL!!!

The fact that your 1st option works means that your citynames.json file is correctly formatted JSON, so there is no need to serialize it again using return Json(data, ...); (and if you did, then you would need to parse it back again using JSON.parse() in the script).

Instead, just return the data as a ContentResult

public ContentResult JsonData()
{
    var data = System.IO.File.ReadAllText(Server.MapPath(@"~/Content/citynames.json"));
    return Content(data);

}

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