views:

56

answers:

2

Hello,

In ASP.NET MVC, we don't have controls which can do stuffs such as autocompletion (we don't have controls at all from Visual Studio like in web forms).

But, Is it possible to still get 'Auto-completion' with a text box in ASP.NET MVC (like with the textbox found on the Google's Home page)?

If this is the case, what's the best way to do so? JQueryUI? or there's someother way of getting that functionality?

Thanks for helping.

+4  A: 

You mean like the one in the jquery ui?

http://jqueryui.com/demos/autocomplete/

chobo2
@Chobo2 -- I've just check the link and that's what I want. Still, I'd like to know if that's the only way to obtain that functionality (i.e. using JQueryUI). If it's the only way, I'm fine with that.
Richard77
Well before JqueryUI. There where other other auto complete plugins. But as far as other ways go. I don't think so. You can roll out your own but that still would be javascript/jquery. I don't think it is possible to make an auto complete just using asp.net MVC(nor even with webforms) as you would have to do a post back every single time to send the letters they are typing in. You need some sort of ajax to make it work.
chobo2
+2  A: 

To use JQuery Autocomplete with ASP.NET MVC you can do the following:

Step 1 : Create the textbox

<%= Html.TextBox("searchBox",null,new { @class="large", autocomplete="on"}) %>

Step 2 : Create action to do search function (I am using NHibernate to query DB, but the key is to return an string with each result delimited by a newline)

public ActionResult Autocomplete(string q) {

  var programs = programRepository
                   .Search(q)
                   .ToList()
                   .ConvertAll(x => x.ProgramName)
                   .ToArray();

  return new ContentResult {Content = string.Join("\n", programs) };
}

Step 3: turn on autocomplete functionality in your HTML (place inside a script block)

$(document).ready(function() {

  $('#searchBox').autocomplete("/Controller/Autocomplete", { autoFill: true, minChars: 2 });

});
Jason Watts