I am trying to pass the value of a selected item from a text box which has been populated using jquery Autocomplete. This is what I have so far:
<script type="text/javascript">
$(function () {
var userId = $('#userID').val();
//http://techbrij.com/987/jquery-ui-autocomplete-asp-net-web-api
$("#autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
url: "/api/Friends/" + userId,
type: 'GET',
cache: false,
data: request,
dataType: 'json',
success: function (json) {
// call autocomplete callback method with results
response($.map(json, function (name) {
return {
label: name.FullName,
value: name.FriendID
};
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#autocomplete").text(textStatus);
}
});
},
select: function (event, ui) {
alert('you have selected ' + ui.item.label + ' ID: ' + ui.item.value);
$('#autocomplete').val(ui.item.label);
return false;
},
messages: {
noResults: '',
results: function () {
}
}
});
});
</script>
View
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>MailMessage</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Recipient.ID)
</div>
<div class="editor-field">
<input type="text" id="autocomplete" />
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Subject)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Subject)
@Html.ValidationMessageFor(model => model.Subject)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Message)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Message)
@Html.ValidationMessageFor(model => model.Message)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Controller
[HttpPost]
public ActionResult Compose(MailMessage mailMessage)
{
mailMessage.MailDate = DateTime.Now;
mailMessage.Recipient = UserManager.GetFullUser(mailMessage.Recipient.ID);
mailMessage.Sender = SDSession.SDUser;
mailMessage.MessageId = Guid.NewGuid();
MailMessageManager.AddMailMessage(mailMessage);
return View("Inbox");
}
This is a cut down version, but it illustrates the issue. It works fine in getting the data from the api, I select the required user and then hit the submit button, but within the controller it expects a MailMessage object, so nothing is passed for the user I have selected in the autocomplete, should I be adding a name attribute to the text box or is there a better way for doing this?