JQuery AutoComplete from a C# Dictionary in MVC4

hi,

Today I faced a problem where I want to map a key/value pair to a JQuery autocomplete so that I can have a user search that is going to provide a visible username to the user, and then give me the selected UserId so I can use it in other operations and database transactions, searched the web, but couldn’t find much!, so I decided to share it with you fellas in case nay of you run into this problem. (Note: you have to implement the below close event of the autocomplete so that you can ensure correct display of values in the text box):

in the View

———————-

you’ll need

1) textbox for the Jquery automcomplete (NewUser)

2) hiddent field to save the selected value (selectedNewUser)

3) hiddent field to set the selected Label (remember if you dont do this, you’ll end up having the value displayed in the autocomplete textbox instead of the Label) (selectedNewUserLabel)

<input type=”text” Id=”NewUser” value=”” />

<input type=”hidden” id=”selectedNewUser” value=”” />
<input type=”hidden” id=”selectedNewUserLabel” value=”” />

//then javascript

<script>

$(function () {

//form an array of Label and Value from the Dictionary
var _source = [];
@foreach (var item in Model.Dictionary1)
{
<text>
_source.push({

value:’@item.Key’,
label:’@item.Value’

});
</text>
}

$(“#Newuser”).autocomplete({
source: _source,
autoFill: true,

select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;

//save the value in the hidden field
$(‘#selectedNewuser’).val(value);
//set the textfield again to the name

$(‘#selectedNewuserLabel’).val(label);

},

close: function (event, ui) {

$(“#Newuser”).val($(‘#selectedNewuserLabel’).val());

}

});

});

Leave a comment