Given the following classes and controller action method:
public School
{
public Int32 ID { get; set; }
publig String Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street1 { get; set; }
public string City { get; set; }
public String ZipCode { get; set; }
public String State { get; set; }
public String Country { get; set; }
}
[Authorize(Roles = "SchoolEditor")]
[AcceptVerbs(HttpVerbs.Post)]
public SchoolResponse Edit(Int32 id, FormCollection form)
{
School school = GetSchoolFromRepository(id);
UpdateModel(school, form);
return new SchoolResponse() { School = school };
}
And the following form:
<form method="post">
School: <%= Html.TextBox("Name") %><br />
Street: <%= Html.TextBox("Address.Street") %><br />
City: <%= Html.TextBox("Address.City") %><br />
Zip Code: <%= Html.TextBox("Address.ZipCode") %><br />
Sate: <select id="Address.State"></select><br />
Country: <select id="Address.Country"></select><br />
</form>
I am able to update both the School instance and the Address member of the school. This is quite nice! Thank you ASP.NET MVC team!
However, how do I use jQuery to select the drop down list so that I can pre-fill it? I realize that I could do this server side but there will be other dynamic elements on the page that affect the list.
The following is what I have so far, and it does not work as the selectors don't seem to match the IDs:
$(function() {
$.getJSON("/Location/GetCountryList", null, function(data) {
$("#Address.Country").fillSelect(data);
});
$("#Address.Country").change(function() {
$.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
$("#Address.State").fillSelect(data);
});
});
});
From Google Groups:
Use two backslashes before each special character.
A backslash in a jQuery selector escapes the next character. But you need two of them because backslash is also the escape character for JavaScript strings. The first backslash escapes the second one, giving you one actual backslash in your string - which then escapes the next character for jQuery.
So, I guess you're looking at
$(function() {
$.getJSON("/Location/GetCountryList", null, function(data) {
$("#Address\\.Country").fillSelect(data);
});
$("#Address\\.Country").change(function() {
$.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
$("#Address\\.State").fillSelect(data);
});
});
});
Also check out How do I select an element by an ID that has characters used in CSS notation? on the jQuery FAQ.