我正在尝试从已使用填充的文本框中传递所选项目的值jquery Autocomplete
。这是我到目前为止所拥有的:
<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>
看法
@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>
}
控制器
[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");
}
这是一个精简版,但它说明了这个问题。它可以很好地从 中获取数据api
,我选择所需的用户,然后点击提交按钮,但在控制器中它需要一个MailMessage
对象,所以我在自动完成中选择的用户没有传递任何内容,我应该添加一个name 属性到文本框还是有更好的方法来做到这一点?