我正在动态加载ASP.NET MVC 3 View。在视图中,有一个需要“自动完成”的文本框。代码如下:
@model CountryViewModel
@using (Html.BeginForm("Create", "Country", FormMethod.Post)) {
@Html.ValidationSummary(true)
<div class="field">
@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="field">
@Html.LabelFor(model => model.Description)
@Html.TextBoxFor(model => model.Description)
</div>
<div class="field">
@Html.LabelFor(model => model.Latitude)
@Html.TextBoxFor(model => model.Latitude)
</div>
<div class="field">
@Html.LabelFor(model => model.Longitude)
@Html.TextBoxFor(model => model.Longitude)
</div>
@Html.HiddenFor(model => model.CultureId, new { id = "CultureId" })
}
<script type="text/javascript">
$(document).ready(function () {
$('#Name').autocomplete({
source: function(request, response) {
$.ajax({
url: '@(Url.Action("GetCountriesB", "Country"))',
data: "{ 'countryName': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Country
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
focus: function( event, ui ) {
$( '#Name' ).val( ui.item.Country );
return false;
}
});
});
我在jQuery UI对话框中加载此View。当我使用Firebug进行调试时,似乎没有加载“script”标记,因此自动完成功能无效。
知道这种行为的原因吗?
由于
答案 0 :(得分:0)
你不应该在partials中放置任何脚本。脚本属于单独的javascript文件。它们不应与标记混合使用。所以把你的脚本放到一个单独的函数中:
function hookupAutoComplete() {
// notice that since we have externalized this into a separate js file
// we can no longer use url helpers here => we will fetch the url
// from the textbox
var url = $('#Name').data('url');
$('#Name').autocomplete({
source: function(request, response) {
$.ajax({
url: url,
data: JSON.stringify({ countryName: request.term }),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Country
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
focus: function( event, ui ) {
$( '#Name' ).val( ui.item.Country );
return false;
}
});
}
假设url存储为HTML5 data- *属性:
@Html.TextBoxFor(model => model.Name, new { data_url = Url.Action("GetCountriesB", "Country") })
然后在你的AJAX请求的成功回调中,一旦你将部分加载到DOM调用这个函数:
$.ajax({
url: '/someurl',
success: function(result) {
$('#dialog').html(result);
hookupAutoComplete();
}
});
实际上您可能会尝试从脚本中删除$(document).ready(...)
,它可能确实有效,但我的建议是从您的标记外部化此脚本。
答案 1 :(得分:0)
我遇到了同样的问题,结果发现z-index太低了。它实际上工作,但只是没有显示。