您可以使用jQuery UI 自动完成。让我们举个例子。
我们可以有以下模型:
public class Route
{
public Address Source { get; set; }
public Address Destination { get; set; }
}
public class Address
{
[Required]
[ValidCity("Location", ErrorMessage = "Please select a valid city")]
public string Text { get; set; }
public Location Location { get; set; }
}
public class Location
{
public double? Latitude { get; set; }
public double? Longitude { get; set; }
}
public class Search
{
public Route RouteSearch { get; set; }
public IEnumerable<Route> Results { get; set; }
}
这[ValidCity]
是我们在 Address 类中使用的自定义验证器:
public class ValidCityAttribute : ValidationAttribute
{
private readonly string _locationPropertyName;
public ValidCityAttribute(string locationPropertyName)
{
_locationPropertyName = locationPropertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_locationPropertyName);
if (property == null)
{
return new ValidationResult(string.Format("Unknown property: {0}", _locationPropertyName));
}
var location = (Location)property.GetValue(validationContext.ObjectInstance, null);
var city = value as string;
if (!string.IsNullOrEmpty(city) && location != null && location.Latitude.HasValue && location.Longitude.HasValue)
{
// TODO: at this stage we have a city name with corresponding
// latitude, longitude => we could validate if they match
// right now we suppose they are valid
return null;
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
然后是控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new Search
{
RouteSearch = new Route
{
Source = new Address(),
Destination = new Address()
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(Route search)
{
if (!ModelState.IsValid)
{
return PartialView("_Route", search);
}
// TODO: do the search here and return the results:
var lat1 = Math.PI * search.Source.Location.Latitude.Value / 180;
var lon1 = Math.PI * search.Source.Location.Longitude.Value / 180;
var lat2 = Math.PI * search.Destination.Location.Latitude.Value / 180;
var lon2 = Math.PI * search.Destination.Location.Longitude.Value / 180;
var R = 6371;
var distance = Math.Acos(Math.Sin(lat1) * Math.Sin(lat2) +
Math.Cos(lat1) * Math.Cos(lat2) *
Math.Cos(lon2 - lon1)) * R;
return Json(new { distance = distance });
}
public ActionResult GetLocation(string text)
{
var results = new[]
{
new { city = "Paris", latitude = 48.8567, longitude = 2.3508 },
new { city = "London", latitude = 51.507222, longitude = -0.1275 },
new { city = "Madrid", latitude = 40.4, longitude = -3.683333 },
new { city = "Berlin", latitude = 52.500556, longitude = 13.398889 },
}.Where(x => x.city.IndexOf(text, StringComparison.OrdinalIgnoreCase) > -1);
return Json(results, JsonRequestBehavior.AllowGet);
}
}
对应的~/Views/Home/Index.cshtml
视图:
@model Search
@using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "searchComplete" }))
{
<div id="search">
@Html.Partial("_Route", Model.RouteSearch)
</div>
<p><button type="submit">OK</button></p>
}
~/Views/Home/_Route.cshtml
部分:
@model ToDD.Controllers.Route
<h3>Source</h3>
@Html.EditorFor(x => x.Source)
<h3>Destination</h3>
@Html.EditorFor(x => x.Destination)
和 Address 类 ( ~/Views/Home/EditorTemplates/Address.cshtml
) 的编辑器模板:
@model Address
<span class="address">
@Html.TextBoxFor(x => x.Text, new { data_url = Url.Action("GetLocation") })
@Html.ValidationMessageFor(x => x.Text)
@Html.HiddenFor(x => x.Location.Latitude, new { @class = "lat" })
@Html.HiddenFor(x => x.Location.Longitude, new { @class = "lon" })
</span>
最后一部分是让一切都充满活力。我们首先包含以下脚本(调整您正在使用的 jQuery 和 jQuery UI 的版本):
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
最后我们编写自定义脚本来连接所有内容:
var searchComplete = function (result) {
if (result.distance) {
alert('the distance is ' + result.distance);
} else {
$('#search').html(result);
attachAutoComplete();
}
};
var attachAutoComplete = function () {
$('.address :text').autocomplete({
source: function (request, response) {
$.ajax({
url: $(this.element).data('url'),
type: 'GET',
cache: false,
data: { text: request.term },
context: response,
success: function (result) {
this($.map(result, function (item) {
return {
label: item.city,
value: item.city,
latitude: item.latitude,
longitude: item.longitude
};
}));
}
});
},
select: function (event, ui) {
var address = $(this).closest('.address');
address.find('.lat').val(ui.item.latitude);
address.find('.lon').val(ui.item.longitude);
},
minLength: 2
}).change(function () {
var address = $(this).closest('.address');
address.find('.lat').val('');
address.find('.lon').val('');
});
}
$(document).ready(attachAutoComplete);