0

I've a method in a NamesModel which fetches all the names and returns a list of names:

public static List<NamesModel> GetAllNames()
{
    List<NamesModel> names = new List<NamesModel>();

    // 
    // code to fetch records
    //

    return names;
}

In my controller:

public ActionResult Index()
{
   NamesModel model = new NamesModel();
   model.GetAllNames();

   return View(model);
}

In the view, I've got a textbox:

@Html.TextBox("search-name")

Now in my javascript, I want to fetch all names into a variable either from a model (from method) or from controller, for example:

<script type="text/javascript">

 $(function () {

     var names = ...........
     $(document).ready(function () {
          $('#search-name').autocomplete({
               source: names
          });
     });
 });
</script>

If I use hardcoding then it works but I want to use the names stored in the db. Is it possible?

hardcoding example:

var names = ["abc", "xyz"];

3 Answers 3

1

You could use Ajax and Json for this

For your controller:

[HttpPost]
public JsonResult GetAllNames()
{
   List<NamesModel> names = new List<NamesModel>();

   // 
   // code to fetch records
   //

   return Json(names);
}

Or for debugging so you can view the json in browser:

public JsonResult GetAllNames()
{
   List<NamesModel> names = new List<NamesModel>();

   // 
   // code to fetch records
   //

   var result = Json(names);
   result .JsonRequestBehavior = JsonRequestBehavior.AllowGet;
   return result ;
}

(note this is actually jquery but since you use document.ready you've allready included jquery)

in your javascript make a call to the method above:

$.getJSON(@Url.Content("~/ControllerName/GetAllNames/"), function (result) {
         var ListWithNames = data;
});
Sign up to request clarification or add additional context in comments.

Comments

0

The "source" options property can be a string wich points to the URL which return json data (http://api.jqueryui.com/autocomplete/#option-source)

Comments

0

The best solution to my problem is in this blog: http://theycallmemrjames.blogspot.co.uk/2010/03/jquery-autocomplete-with-aspnet-mvc.html

Thanks to everyone who tried to help me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.