xSea xSea - 1 month ago 9
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()
}).ToList();


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

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

$(function(){

  $("#Name").change(function(){

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

     $.get(url + "?id=" + siteId, function (data) {
            $("#address").html(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.

Comments