Skip to content
Tim Wilson edited this page Feb 24, 2016 · 3 revisions

FAQ

Is there an event after item selected?

Yes, there is an event after the item is selected. In the typeahead.mvc.model.js file in the Scripts folder, you may add whatever code you need to the function onselected(). This project is meant to get you started with Typeahead and manual changes to the files that I create may be needed for your particular project.

Can I use AutocompleteFor within a for loop?

Yes, with the latest version of this component, you may pass in the element of the array you are looping over for both the idExpression and valueExpression. For example, you can do something like this:

@for (int i = 0; i < Model.SelectedIngredients.Count; i++) {
	<tr id=@string.Format("ingredientRow{0}", i) class="hidden">
		<td>
			<div class="col-md-10">
				@Html.HiddenFor(model => model.SelectedIngredients[i])
				@Html.AutocompleteFor(model => model.SelectedIngredientsNames[i], model => model.SelectedIngredients[i], i,
					"GetIngredients", "Recipes", false, new { htmlAttributes = new { @class = "form-control" } })
			</div>
		</td>
	</tr>
}

And this html will be generated:

<tr id=ingredientRow0 class="hidden">
	<td>
		<div class="col-md-10">
			<input data-val="true" data-val-number="The field Nullable`1 must be a number." id="SelectedIngredients_0_" name="SelectedIngredients[0]" type="hidden" value="" />
			<input class="form-control typeahead" data-autocomplete-id-field="SelectedIngredients_0_" data-autocomplete-url="/Recipes/GetIngredients" id="SelectedIngredientsNames_0_" name="SelectedIngredientsNames[0]" type="text" value="" />
		</div>
	</td>
</tr>

Can I add my own HTML attributes to the code that AutocompleteFor generates (e.g. CSS classes, event handlers etc.)?

Yes, the latest version of this component includes that functionality. Just specify the optional htmlAttributes in the additionalViewData like you normally would for an MVC component, such as EditorFor. A code example is included in my CSHTML code above but here it is again for emphasis (note the anonymous type starting with "new { htmlAttributes ... }":

@Html.AutocompleteFor(model => model.SelectedIngredientsNames[i], model => model.SelectedIngredients[i], i,
                                    "GetIngredients", "Recipes", false, new { htmlAttributes = new { @class = "form-control" } })