jQuery 使用 MVC 4 / Razor 自动完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13455610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Autocomplete with MVC 4 / Razor
提问by Newm
I think I am missing something obvious while attempting to add autocomplete functionality in MVC 4. From what I have found in other posts I have been able to put together an example however the method in my controller is not being called.
我想我在尝试在 MVC 4 中添加自动完成功能时遗漏了一些明显的东西。根据我在其他帖子中的发现,我已经能够将一个示例放在一起,但是我的控制器中的方法没有被调用。
What I have tried so far...
到目前为止我尝试过的...
_Layout
_布局
@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/jqueryval")
Controller
控制器
Public Function Numbers(term As String) As ActionResult
Return Json(New String() {"one", "two", "three", "four", "five", "six"}, JsonRequestBehavior.AllowGet)
End Function
View (I have hard coded the Home/Numbers for now)
查看(我现在已经硬编码了 Home/Numbers)
<div class="editor-label">
@Html.LabelFor(Function(model) model.Number)
</div>
<div class="editor-field">
@Html.EditorFor(Function(model) model.Number)
@Html.ValidationMessageFor(Function(model) model.Number)
</div>
<script type="text/javascript">
$(function () {
$("#Number").autocomplete({
source: 'Home/Numbers',
minLength: 1
});
});
</script>
When I run my app and type in the textbox nothing happens. I have put a breakpoint in the "Numbers" function and it seems that it is never called.
当我运行我的应用程序并在文本框中输入时,没有任何反应。我在“Numbers”函数中放置了一个断点,它似乎从未被调用过。
My project can be found here http://www.filedropper.com/testapp
我的项目可以在这里找到http://www.filedropper.com/testapp
采纳答案by nemesv
If you have the @Scripts.Render
lines at the bottom of the body
element in the layout and after the @RenderBody()
you need to put your script in the scripts
section:
如果您在布局@Scripts.Render
中的body
元素底部有线条,并且在@RenderBody()
您需要将脚本放在该scripts
部分之后:
@section scripts
<script type="text/javascript">
$(function () {
$("#Number").autocomplete({
source: '@Url.Action("Numbers","Home")',
minLength: 1
});
});
</script>
End Section
Because your script depends on jQuery so jQuery should be loaded first.
因为您的脚本依赖于 jQuery,所以应该首先加载 jQuery。
Or just move your @Scripts.Render
declaration into the head
in the layout then you don't need to put your code into the scripts
section (but you are better off with using the section)
或者只是将您的@Scripts.Render
声明移动到head
布局中,然后您就不需要将代码放入该scripts
部分(但最好使用该部分)
回答by Amirhossein Mehrvarzi
I suggest you to control errors in Chrome to ensure that jQuery libraries working properly. if there is no problem, Try this script :
我建议您控制 Chrome 中的错误以确保 jQuery 库正常工作。如果没有问题,试试这个脚本:
$(document).ready(function () {
$("#Number").each(function () {
$(this).autocomplete({ source: $(this).attr("data-autocomplete") });
});
});
Then in your Razor (C#):
然后在你的 Razor (C#) 中:
<input type="text" id="Number" data-autocomplete="@Url.Action("Action","Controller")" autocomplete="on" />
If you want to use Razor Html Helpers instead of using 'input' tag, The id attribute is the same name of Model.Member. Notice that in Controller, you must input string with the 'term' name, as written in your code. For security reasons, you must avoid using parameters in js file that shows the site technology. The method declared above never uses js file to get address of resource.
如果你想使用 Razor Html Helpers 而不是使用 'input' 标签,id 属性与 Model.Member 同名。请注意,在 Controller 中,您必须输入带有“term”名称的字符串,如代码中所写。出于安全原因,您必须避免在显示站点技术的 js 文件中使用参数。上面声明的方法从不使用 js 文件来获取资源地址。
回答by Saurabhbhatt
This is the total code project of autocomplete textbox example .
这是自动完成文本框示例的总代码项目。
回答by Jyoti Kumari
For Viewpage
对于视图页面
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<input type="text" id="txtmasterserach" name="txtmasterserach" placeholder="City, region, district or specific hotel" autocomplete="off"/>
<input type="hidden" name="hidenkeyvalues" id="MovieID" />
<script type="text/javascript">
$(document).ready(function () {
$("#txtmasterserach").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Company/getautobox",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { value: item.Id, label: item.name };
}))
}
})
},
select: function (event, ui) {
$("#MovieID").val(ui.item.value);
$("#txtmasterserach").val(ui.item.label);
event.preventDefault();
return false;
},
focus: function (event, ui) {
$("#MovieID").val(ui.item.value);
// $("#txtmasterserach").val(ui.item.label);
event.preventDefault();
return false;
},
messages: {
noResults: "", results: ""
}
});
});
</script>
For Controller :
对于控制器:
public class companyController : Controller
{
public JsonResult getautobox(String Prefix)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
SqlCommand cmd = new SqlCommand("procedurename", con);
cmd.Parameters.AddWithValue("@prefix", Prefix);
cmd.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
List<autosearchdatalist> auto = new List<autosearchdatalist>();
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
auto.Add(new autosearchdatalist
{
Id = ds.Tables[0].Rows[i]["Id"].ToString(),
name = ds.Tables[0].Rows[i]["hotelname"].ToString()
});
}
}
if (ds.Tables[1].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
{
auto.Add(new autosearchdatalist {
Id = ds.Tables[1].Rows[i]["Id"].ToString(),
name = ds.Tables[1].Rows[i]["hotelname"].ToString()
});
}
}
if (ds.Tables[2].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[2].Rows.Count; i++)
{
auto.Add(new autosearchdatalist
{
Id = ds.Tables[2].Rows[i]["Id"].ToString(),
name = ds.Tables[2].Rows[i]["hotelname"].ToString()
});
}
}
String msg = "";
return Json(auto);
}
}
Keep router setting default otherwise action will not call
保持路由器设置默认否则动作不会调用
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "company", action = "Index", id = UrlParameter.Optional }
);
}
}