[英]Read and Show .Json file in an auto-complete search using ASP.NET MVC
I made a json file contain City names of a country.I want to show these City name as autocomplete search on View using MVC.My Cityname.Json file look like this - 我制作了一个包含国家城市名称的json文件。我想使用MVC在View上以自动完成搜索的形式显示这些城市名称。我的Cityname.Json文件看起来像这样-
Cityname[
{
"id": 1,
"City": "Flensburg"
},
{
"id": 2,
"City": "Kiel"
},
{
"id": 3,
"City": "Lübeck"
},
{
"id": 4,
"City": "Neumünster"
},
{
"id": 5,
"City": "Brunsbüttel"
}
]
My model Class for City object is- 我的城市对象模型类是-
public class City
{
public string id{get:set;}
public string City { get; set; }
}
In my home controller in action-result index I desrialize Json file to show on view 在我的家庭控制器中的动作结果索引中,我对Json文件进行脱盐处理以显示在视图上
public ActionResult Index()
{
using (StreamReader r = new StreamReader("file.json"))
{
string json = r.ReadToEnd();
List<CityName> items = JsonConvert.DeserializeObject<List<CityName>>(json);
}
return View();
}
Now View class I made search box , where I want to get all city name in auto-completed way. 现在,我在View类中创建了搜索框,我想在其中以自动完成的方式获取所有城市名称。 But i am not how to proceed with it 但我不是如何进行
<div class="search-form">
<form action="index.html" method="get">
<div class="input-group">
<input type="text" placeholder="Enter Location Name" name="search" id="CitySearch" class="form-control input-lg">
<div class="input-group-btn">
<script type="text/javascript" src="~/App_Data/Cityname.josn">
$(function () {
$("#CitySearch").autocomplete
});
</script>
<button class="btn btn-lg btn-primary" type="submit">
<a href="~/Home/Search">Search</a>
</button>
</div>
</div>
</form>
My _Layout.cshtml file look like this- 我的_Layout.cshtml文件看起来像这样-
@using OpenStreetMapService.Helpers
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Call List Service | @ViewBag.Title</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'>
<!-- Add local styles, mostly for plugins css file -->
@if (IsSectionDefined("Styles"))
{@RenderSection("Styles", required: false)}
<!-- Add jQuery Style direct - used for jQGrid plugin -->
<link href="@Url.Content("~/Scripts/plugins/jquery-ui/jquery-ui.css")" rel="stylesheet" type="text/css" />
<!-- Primary Inspinia style -->
@Styles.Render("~/Content/css")
@Styles.Render("~/font-awesome/css")
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
</head>
<body>
<!-- Skin configuration box -->
@*@Html.Partial("_SkinConfig")*@
<!-- Wrapper-->
<!-- PageClass give you ability to specify custom style for specific view based on action -->
<div id="wrapper" class="@Html.PageClass()">
<!-- Navigation -->
@Html.Partial("_Navigation")
<!-- Page wraper -->
<div id="page-wrapper" class="gray-bg @ViewBag.SpecialClass">
<!-- Top Navbar -->
@Html.Partial("_TopNavbar")
<!-- Main view -->
@RenderBody()
<!-- Footer -->
@Html.Partial("_Footer")
</div>
<!-- End page wrapper-->
<!-- Right Sidebar -->
@Html.Partial("_RightSidebar")
</div>
<!-- End wrapper-->
<!-- Section for main scripts render -->
@Scripts.Render("~/bundles/jquery")
@*@Scripts.Render("~/plugins/jquery-ui/jquery-ui.min.js")*@
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/plugins/slimScroll")
@Scripts.Render("~/bundles/inspinia")
<!-- Skin config script - only for demo purpose-->
@Scripts.Render("~/bundles/skinConfig")
<!-- Handler for local scripts -->
@RenderSection("scripts", required: false)
</body>
</html>
If your JSON list is static data you can store a list in the javascript if that's easier. 如果您的JSON列表是静态数据,则可以将列表存储在javascript中(如果更简单)。
$(function() { var Cityname = [{ "value": 1, "label": "Flensburg" }, { "value": 2, "label": "Kiel" }, { "value": 3, "label": "Lübeck" }, { "value": 4, "label": "Neumünster" }, { "value": 5, "label": "Brunsbüttel" }] $("#city").autocomplete({ source: Cityname }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <input id="city">
Of course a better design method can be preferred but basicly: 当然,更好的设计方法可能是首选,但基本上是:
Put this script code inside the <head>
tag of your HTML code: 将此脚本代码放入HTML代码的<head>
标记内:
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$("#cities").autocomplete({
source: function(request, response) {
$.getJSON("citynames.json", request, function(data) {
var i, suggestions = [];
$.each(data.cities, function(i, val) {
if (val.name.toLowerCase().indexOf(request.term.toLowerCase()) > -1) {
suggestions.push({
label: val.name,
value: val.id
});
}
});
response(suggestions);
});
}
});
});
</script>
</head>
Add this HTML code into your View file: 将此HTML代码添加到您的View文件中:
<div class="ui-widget">
<label for="cities">Cities: </label>
<input id="cities" />
</div>
And put this JSON file into the same directory with the file where you put the script above naming it as 'citynames.json': 并将此JSON文件与将脚本命名为“ citynames.json”的文件放在同一目录中:
{
"cities": [{
"id": 1,
"name": "Flensburg"
}, {
"id": 2,
"name": "Kiel"
}, {
"id": 3,
"name": "Lübeck"
}, {
"id": 4,
"name": "Neumünster"
}, {
"id": 5,
"name": "Brunsbüttel"
}]
}
See this plunker for a running example 有关运行示例,请参见此插件
My new Index.cshtml file look like this- 我的新Index.cshtml文件看起来像这样-
<script type="text/javascript">
$(function () {
$("#cities").autocomplete({
source: function (request, response) {
$.getJSON("Cityname.json", request, function (data) {
var i, suggestions = [];
$.each(data.cities, function (i, val) {
if (val.name.toLowerCase().indexOf(request.term.toLowerCase()) > -1) {
suggestions.push({
label: val.name,
value: val.id
});
}
});
response(suggestions);
});
}
});
});
</script>
<div class="search-form">
<form action="index.html" method="get">
<div class="input-group">
<input type="text" placeholder="Please enter City Name" name="cities" input id="cities" class="form-control input-lg">
<div class="input-group-btn">
<button class="btn btn-lg btn-primary" type="submit">
<a href="~/Home/Search">Search</a>
</button>
</div>
</div>
</form>
-- Js Code ------ -Js代码------
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
method: "POST",
url: "/Home/GetCityList",
dataType: 'JSON',
success: function (data) {
if (data != null && data != undefined) {
$('#cityId').typeahead({
source: data,
autoSelect: true
});
}
}
})
})
</script>
--- Controller --- -控制器-
[HttpPost]
public JsonResult GetCityList()
{
string text;
var fileStream = new FileStream(@"E:\NLogErrors\File.Json", FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
text = streamReader.ReadToEnd();
}
List<City> items = JsonConvert.DeserializeObject<List<City>>(text);
return Json(items);
}
--- Model --- -型号-
public class City
{
public string value { get; set; }
public string name { get; set; }
}
--- JSON File Format --- -JSON文件格式-
[
{
"value": 1,
"name": "Flensburg"
},
{
"value": 2,
"name": "Kiel"
},
{
"value": 3,
"name": "Lübeck"
},
{
"value": 4,
"name": "Neumünster"
},
{
"value": 5,
"name": "Brunsbüttel"
}
]
--- HTML --- -HTML-
<input type="text" autocomplete="off" id="cityId" /> (same way you can use it with razor.)
I have Used bootstrap3-typeahead.js for autosuggest binding 我已经使用bootstrap3-typeahead.js进行自动建议绑定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.