Search code examples
jqueryasp.net-mvc-3jquery-tokeninput

Jquery Token Input not populating values from database, in ASP.NET MVC 3


I am new to jQuery Token Input and am learning through this tutorial.

What I want to do ?

I want to show values from database as the user types in the value into the textbox using jQuery Token input.

What have I tried so far ?

So far, this is what my view looks like...

View

<p>
Getting data from database using <i>token Input</i> =>
<input type="text" id="selectDb" />
</p>

<script type="text/javascript">
    $(document).ready(function () {

        $("#selectDb").tokenInput("@Url.Action("Search")");

    });
</script> 

</div>

and below is my controller action.

Controller Code

[HttpGet]
public JsonResult Search(string q)
{
    var searchResult = Helper.SearchContact(q);
    return Json(searchResult, JsonRequestBehavior.AllowGet);
}

and my Helper.cs class code is...

public static class Helper
{
    public static CRUDEntities1 Entities = new CRUDEntities1();

    public static IEnumerable<Contact> SearchContact(string s)
    {
        var searchResults = Entities.Contacts.Where(item => item.Name.Contains(s));

        return searchResults;
    }
}

I am not sure where I am going wrong, please guide me on this. Thanks.

Edit : Contact is an entity model class generated by the EntityFramework and has one int field called 'id' and two string fields called 'city' and 'name'.


Solution

  • Update : Using jQuery Tokeninput with ASP.NET MVC 3 Razor

    Thanks @bhuvin and others.

    Solved, had to do this...

    [HttpGet]
    public JsonResult Search(string q)
    {
        var searchResults = Helper.SearchContact(q);
        var jsonResult = searchResults.Select(results => new { id = results.Id, name = results.Name, city = results.City });
        return Json(jsonResult, JsonRequestBehavior.AllowGet);
    }
    

    and found this in TokenInput's documentation here.

    Your script should output JSON search results in the following format:

    [
        {"id":"856","name":"House"},
        {"id":"1035","name":"Desperate Housewives"},
        ...
    ]