I am building a website using ASP.NET MVC and entity framework. I have a DB table with Country info:
CountryID int;
ShortName nvarchar;
CountryCode nvarchar;
In my View I have:
<div class="editor-field"><%: Html.DropDownListFor(model => model.address.CountryID, Model.countriesList, "<--Select Country-->") %></div>
<div class="display-field"><%: Html.TextBoxFor(m => m.phone.CountryCode)%>></div>
The list I pass onto the view is:
countriesList = new SelectList(countries, "CountryID", "ShortName");
Update The javascript code:
<script src="/Scripts/jquery-1.4.1.min.js" language="javascript" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#address.CountryID").change(function()
{
$.get("/PersonalInfo/GetCountryCode", $(this).val(), function(data)
{
$("#phone.CountryCode").val(data);
});
});
});
And the controller method:
public ActionResult GetCountryCode(int id)
{
Country c = personalInfoRepository.GetUserCountryByID(id);
string countryCode = c.PhoneCode;
return Content(countryCode);
}
</script>
What I want to do is to populate the display field with the corresponding CountryCode every time the user selects a different country from the dropdown. I understand ajax can be used to achieve this but unfortunatelly I have no experience with it. I would appreciate any help with the code or some links to easy enough tutorials for beginners.
Would it be possible to do it without posting back to the server if I passed a countryCodeList along the countriesList?
Here is a great tutorial with 3 different methods for creating cascading dropdowns with ASP.NET MVC - http://stephenwalther.com/blog/archive/2008/09/07/asp-net-mvc-tip-41-creating-cascading-dropdown-lists-with-ajax.aspx
The concept for populating a textbox will be similar. First of all you will need a controller action that will return the correct country code for a given country:
public ActionResult GetCountryCode(int countryId)
{
//logic to find country code goes here
string countryCode = "1";
return Content(countryCode);
}
Now you will need some javascript to bind to the change event of your country dropdown and call your controller action via ajax. I recommend using jquery:
<script type="text/javascript">
$(document).ready(function()
{
$("#address_CountryID").change(function()
{
$.get("/Countries/GetCountryCode", $(this).val(), function(data)
{
$("#phone_CountryCode").val(data);
});
});
});
</script>