Yasser Shaikh
Yasser Shaikh

Reputation: 47784

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'.

Upvotes: 2

Views: 2643

Answers (2)

Dhiren Patel
Dhiren Patel

Reputation: 11

This works for me:

In view:

<h2 id="theme">Facebook Theme</h2>
<div>
    <input type="text" id="authorlist" name="q" data-autocomplete="@Url.Action("GetAuthors", "Home")" />

</div>

In script(javascript)

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

        $("#authorlist").tokenInput("@Url.Action("Search")", {
            theme: "facebook",
            preventDuplicates: true
        });

    });
</script>

In controller:

[HttpGet]
public JsonResult Search(string q)
{
    q = q.ToUpper();
    var authors = db.StudentDB
        .Where(a => a.name.ToLower().StartsWith(q))
        .Select(a => new { id = a.id, name = a.name });

    return Json(authors,  JsonRequestBehavior.AllowGet);
}

Upvotes: 1

Yasser Shaikh
Yasser Shaikh

Reputation: 47784

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"},
    ...
]

Upvotes: 2

Related Questions