Search code examples
javascriptasp.net-mvckendo-uiautocompletekendo-template

Kendo autocomplete template img src from database


There are many examples how to set icon from static content. For example:

Html.Kendo().AutoComplete()
    .Name("employess")
    .Placeholder("Find Product..")
    .DataTextField("Name")
    .HighlightFirst(true)
    .Template("<span><img src='/Content/Images/default-photo.jpg' " +
    "width='20' height='20' />&nbsp;${data.Name}</span>")
...

Is it possible to set image src from database by ${data.ImageId}? I tried to make controller method and paste Url.Action instead of default-photo but compiler doesn't understand what do I want to do.

Thanks for advance!


Solution

  • If you have the image name in your data object and the image is in your Content folder, you can use Url.Content() to get the path to it, as showed here. So your template could be like:

    .Template("<span><img src='" + Url.Content("~/Images/") + "${data.ImageName}' " +
    "width='20' height='20' />&nbsp;${data.Name}</span>")
    

    The url will result in something like: Content/Images/image.jpg.

    But if you have only the id and need to generate the image as a http response, you can create an action method for that, as showed here. So your template would be:

    .Template("<span><img src='" + Url.Action("GetImage", "Search") + "/${data.ImageId}' " +
    "width='20' height='20' />&nbsp;${data.Name}</span>")
    

    The url will result in something like: Search/GetImage/1.

    In both cases you somehow concat the Javascript variable in an ASP.Net string, as showed in this answer of a friend of mine.