xSea xSea - 1 year ago 78
ASP.NET (C#) Question

Select dropdownlist display string of data under it. In MVC

How do I get the string value under the selected dropdownlist value?

var SiteResponse = repository.Sites.GetAll();

SiteResponse.result returns a few parameter "Address","Name" and "ID"

ViewBag.SiteName = SiteResponse.Result.Select(x => new SelectListItem
Text = x.Name,
Value = x.Id.ToString()

I put the name and ID into the dropdownlist mvc view
@Html.DropDownList("Name", (IEnumerable<SelectListItem>)ViewBag.SiteName, new { @class = "form-control" })

I want to display the address of the selected dropdownlist value in another element. how do i do it? be it Jquery or any other C# methods

Answer Source

You should listen to the change event of the SELECT element, get the selected option value ( the Id of the selected site) and make an ajax call to server passing this id. Have the server return the address (and other info as needed). Your ajax method's success/done event can use the data coming back to update the DOM.

Assuming you have an element in your page with id "address" where you want to show the address of the selected site, You may keep the (base) url to the action method which returns the address for the selected site id as the html 5 data attribute.

 @Html.DropDownList("Name", (IEnumerable<SelectListItem>)ViewBag.SiteName, 
                new { @class = "form-control" , @data_addressurl=Url.Action("GetAddress")})
<div id="address"></div>

And the javascript code to handle the change event on the select element



     var siteId = $(this).val(); 
     var url = $(this).data("addressurl");

     $.get(url + "?id=" + siteId, function (data) {



Assuming GetAddress accepts a siteId and return the address

public ActionResult GetAddress(int id)
   //to do : Get Address from Id and return
   return Json("110 William St 28th Floor,New York",JsonRequestBehavior.AllowGet);

Here i am returning a simple string. You may also return an object and inside the ajax success call back, access the specific properties as needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download