Ajax Auto Complete in ASP.Net MVC project - How to display a an object's name but actually save it's

Posted by Ben on Stack Overflow See other posts from Stack Overflow or by Ben
Published on 2010-02-24T15:38:24Z Indexed on 2010/03/09 7:06 UTC
Read the original article Hit count: 264

I have implemented the Ajax Autocomplete feature in my application using a web service file that querys my database and it works great. One problem I am having is allowing the user to see the item's name, as that's what they are typing in the textbox, but when they select it, it saves the item's ID number instead of the actual name. I want it to behave much like a dropdown list, where I can specify what is seen and entered vs. what is actually saved in the database (in this case, the product ID instead of it's name.)

I have this text box in my view, along with the script:

<script type="text/javascript">
    Sys.Application.add_init(function() {
        $create(

        AjaxControlToolkit.AutoCompleteBehavior, {
            serviceMethod: 'ProductSearch',
            servicePath: '/ProductService.asmx',
            minimumPrefixLength: 1,
            completionSetCount: 10
        },
        null,
        null,
        $get('ProductID'))
    });
    </script>
<p>
    <label for="ProductID">Product:</label>
    <%= Html.TextBox("ProductID", Model.Products)%>
    <%= Html.ValidationMessage("ProductID", "*")%>
</p>

Here's what is in my asmx file:

public class ProductService : System.Web.Services.WebService
{
    [WebMethod]
    public string[] ProductSearch(string prefixText, int count)
    {
        MyDataContext db = new MyDataContext();

        string[] products = (from product in db.Products
                             where product.ProductName.StartsWith(prefixText)
                             select product.ProductName).Take(count).ToArray();
        return products;
    }
}

Can anyone help me figure this out? I'm using this so they can just start typing instead of having a dropdown list that's a mile long...

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about asp.net-ajax