0

也许我在考虑这个错误的方式,来自最近对 WPF 和 MVVM 的研究,但我的 Web 项目中有以下 ViewModel。

public class Route
{
    public Address Source {get; set;}
    public Address Destination {get; set;}
}

public class Address
{
    public string Text {get; set;}
    public Location Location {get; set;}
}

puclic class Location
{
    [Required]
    public double? Latitude {get; set;}
    [Required]
    public double? Longitude {get; set;}
}

public class Search
{
    public Route {get; set;}
    public IEnumerable<Route> Results {get; set;}
}

我有以下观点(_ 前缀的观点是部分的)

   Home.cshtml - the main page, has @model Search with call to @Html.Partial("_Route", Model.Search) inside an Ajax.BeginForm.

   _Route.cshtml - @model Route, with two Html.Partials for _Address, one for Model.Source and one for Model.Destination

   _Address.cshtml - @model.Address, with a text box which should be "bound" to the Address.Text property.

如果不清楚我要做什么 - 我试图让用户在源框和目标框中输入一些搜索文本,然后得到结果。当用户选择自动完成选项之一时,源和目标框应通过 Ajax 自动完成并填充 Address.Location.Latitude 和 Address.Location.Longitude。

最后,一旦用户拥有有效的源和目标位置,Home.cshtml 上的提交按钮应该通过 Ajax 调用以获取搜索结果并将它们绑定到网格。

很标准的东西我猜...

我正在努力以“最干净”的方式完成以下任务:

  1. 由于位置实际上并未显示在地址视图中的任何位置(只是文本),我怎样才能让 ASP.NET MVC 的 DataAnnotations 验证启动并帮助我验证?

  2. 当用户选择 AutoComplete 选项之一时,我如何让 Location 值冒泡回 Home.cshtml,它应该通过 Ajax 调用发布 Route 对象?

  3. 我应该如何维护用户在源和目标中选择的地址的“状态”?将选择处理程序添加到自动完成?但是然后用选定的值做什么呢?

我希望这很清楚......但如果没有,请告诉我,我会尽力澄清。

4

1 回答 1

1

您可以使用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);
于 2012-08-21T12:24:31.660 回答