【发布时间】:2015-07-26 20:31:25
【问题描述】:
我在将带有自动完成功能的脚本连接到我的 Json 控制器时遇到问题。该视图是一个公式,用户可以在其中插入数据,例如使用 datepicker 函数的日期和描述问题的一般文本。整个公式是这样的:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
所有文本框、下拉列表和编辑器都连接到模型,如下所示:
<div class="editor-label">
@Html.LabelFor(model => model.Overview)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Overview)
@Html.ValidationMessageFor(model => model.Overview)
</div>
目前我尝试插入文本框,自动完成应该像这样发生:
<b>Name: </b>
@Html.TextBox("searchTerm", null, new { id = "txtSearch" })
txtSearch 连接到我的脚本 SearchUser.js:
$(function () {
$("#txtSearch").autocomplete({
source: '@url.Action("New1", "Dialog")',
minLength: 1
});
});
当我使用源字符串数组时,会出现自动完成。
JavaScript 注册在视图之上,jQueryUI 注册在 _Layout.cshtml 中。我正在使用 jquery 1.11.3 和 jqueryui 1.11.4 。
在 JsonResult 的控制器 New1 中,您会发现:
public JsonResult Dialog(string search)
{
List<string> users = db
.Users
.Where(p => p.FirstName.ToLower().Contains(search.ToLower()))
.Select(p => p.LastName)
.ToList();
return Json(users, JsonRequestBehavior.AllowGet);
}
当我测试网站并寻找http://localhost:51299/New1/Dialog?search=m
我得到了 json 文件。 json 文件包含以下内容:["Mueller"]
但是当我转到我的公式 http://localhost:51299/New1/Create 并在 TextBox 中插入“m”时没有任何反应。
所以现在我的问题是:我该怎么做才能让它发挥作用?
更新(它正在工作!!!)
啊啊啊它的工作!!!。非常感谢!他无法使用源,所以现在我将其更改为“/New1/Dialog”。 我知道使用直接 url 而不是 '@url.Action("Dialog", "New1")' 不是一个好方法,但我认为他在普通 ' 和 之间没有区别>”。 如果你知道为什么我不能使用@url.Action,我会对它感兴趣。
查看(创建.cshtml)
@Html.TextBox("searchTerm", null, new { id = "searchTerm" })
脚本 (SearchUser.js)
$(function () {
$("#searchTerm").autocomplete({
source: "/New1/Dialog",
minLength: 1
});
});
控制器 (New1Controller.cs)
public JsonResult Dialog(string term)
{
List<string> users = db
.Users
.Where(p => p.LastName.ToLower().Contains(term.ToLower()))
.Select(x => x.LastName)
.ToList();
return Json(users, JsonRequestBehavior.AllowGet);
}
【问题讨论】:
-
您是否使用浏览器的开发者工具查看请求是否成功完成?如果你在
Dialog操作中放置一个断点,它会被命中吗? -
是的,我已经这样做了,它没有受到打击。
-
@url.Action("New1", "Dialog")指向DialogController中的方法New1()。要在New1Controller中点击Dialog(),它必须是@url.Action("Dialog", "New1") -
谢谢,这也是一个很大的错误,但它也没有解决问题。
-
啊,我明白了。您不能在 JavaScript 文件中使用 razor 助手,因此永远不会处理
@Url.Action(...)。
标签: c# jquery json asp.net-mvc-4 jquery-ui-autocomplete