ASP.NET MVC 4嵌套ViewModels Ajax

时间:2012-08-21 03:29:50

标签: asp.net-mvc mvvm asp.net-mvc-4

也许我正在考虑这个错误的方式,来自最近对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.

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

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

我觉得很标准的东西......

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

  1. 由于Location实际上并未显示在Address视图中的任何位置(只是Text),我如何才能启动ASP.NET MVC的DataAnnotations验证并帮助我验证?

  2. 当用户选择其中一个AutoComplete选项时,如何让Location值冒泡回Home.cshtml,这应该通过Ajax调用POST一个Route对象?

  3. 如何在源和目标中维护用户所选地址的“状态”?在AutoComplete中添加Select处理程序?但是然后用选定的值做什么?

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

1 个答案:

答案 0 :(得分:1)

您可以使用jQuery UI autocomplete。我们来举个例子吧。

我们可以有以下型号:

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; }
}

这是我们在Address类上使用的[ValidCity]自定义验证器:

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);