I am giving you this example with context to Customers Table of Northwind Database. You can get reference of downloading and configurating entity framework for Northwind here
ASP.Net entity Framework GridView Custom Paging Example
Then create a new MVC Sample project and add the following Model and Data Class in Models folder
public class CustomerModel
{
public string ID { get; set; }
public List<SelectListItem> CustomersList { get; set; }
}
public class CustomerData
{
public List<SelectListItem> GetCustomers()
{
NorthwindEntities entities = new NorthwindEntities();
return (from customer in entities.Customers
select new SelectListItem
{
Text = customer.ContactName,
Value = customer.CustomerID
}).ToList();
}
public Customer GetCustomerCity(string customerId)
{
NorthwindEntities entities = new NorthwindEntities();
return (from customer in entities.Customers
where customer.CustomerID == customerId
select customer).FirstOrDefault();
}
}
And in the Home Controller I have the following code
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
CustomerData data = new CustomerData();
CustomerModel model = new CustomerModel();
model.CustomersList = data.GetCustomers();
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View(model);
}
[HttpPost]
public ActionResult GetCustomerCity(string customerId)
{
var request = HttpContext.Request;
CustomerData data = new CustomerData();
CustomerModel model = new CustomerModel();
return Json(data.GetCustomerCity(customerId));
}
}
Finally on the About View add a DropDown with some jQuery code to populate the result on DropDown change.
Basically I am populating Customer Name and Id in DropDown and when DropDown value is changed the City is populated using jQuery AJAX
<h2>
About</h2>
<% using (Html.BeginForm())
{ %>
<%: Html.Label("Select Customer: ")%>
<%:Html.DropDownListFor(customer => customer.ID, Model.CustomersList, new { id = "ddlCustomers" })%>
<br />
<br />
<%: Html.Label("City: ")%><span id = "lblCity"></span>
<script src="<%: Url.Content("~/Scripts/jquery-1.4.1.js") %>" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#ddlCustomers").change(function () {
var c = $(this).val();
// var a = JSON.stringify({ customerId: $(this).val() };
$.ajax({
url: '<%: Url.Content("~/Home/GetCustomerCity")%>',
type: 'POST',
data: { customerId: c },
cache: false,
success: function (data) {
$("#lblCity").html(data.City);
},
error: function (data) {
}
});
});
});
</script>
<%} %>