Maybe I’m thinking about this the wrong way, coming from a recent delve into WPF and MVVM, but I have the following ViewModels in my Web project.
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;}
}
I have the following views (_ prefixed views are partial)
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.
In case it’s not clear what I’m trying to do – I’m trying to get the user to enter some search text in a source box and a destination box and then get results. The Source and Destination boxes should AutoComplete via Ajax and populate Address.Location.Latitude and Address.Location.Longitude when the user picks one of the AutoComplete choices.
Finally, once the user has valid Source and Destination Locations, the Submit button on the Home.cshtml should call via Ajax to get the search results and bind them to a grid.
Pretty standard stuff I guess…
I’m struggling with the “cleanest” way to accomplish the following:
-
Since Location isn’t actually displayed anywhere in the Address view (just Text), how can I get ASP.NET MVC’s DataAnnotations validation to kick in and help me validate?
-
When the user picks one of the AutoComplete choices, how do I get the Location values to bubble back up to the Home.cshtml which should POST a Route object via an Ajax call?
-
How should I maintain the “state” of the user’s selected Addresses in the Source and Destination? Add a Select handler to the AutoComplete? But then do what with the selected value?
I hope this is clear…but if not, let me know and I’ll try to clarify.
You could use jQuery UI autocomplete. Let’s take an example.
We could have the following models:
And here’s the
[ValidCity]custom validator that we used on the Address class:Then a controller:
a corresponding
~/Views/Home/Index.cshtmlview:The
~/Views/Home/_Route.cshtmlpartial:and the editor template for the Address class (
~/Views/Home/EditorTemplates/Address.cshtml):The last part is to make everything alive. We start by including the following scripts (adjust the versions of jQuery and jQuery UI that you are using):
and finally we write our custom script to wire everything up: