Message Appears When Selecting Value in a Dropdownlist

0

I created a dropdownlist in asp.net linked to a database. Now I want a message to appear as soon as one of the db values is selected.

(Ex: A dropdownlist with three values "A", "B", "C".) When I click on "B", a message appears saying: "You chose B.

Follow the code

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult dbExample()
    {
        copaDBEntities entity = new copaDBEntities();
        var getCopaList = entity.copa.ToList();
        SelectList list = new SelectList(getCopaList, "id", "ano");
        ViewBag.copalistano = list;

        return View();
    }
}

View

@{
    ViewBag.Title = "dbExample";
}

<h2>Copa do Mundo</h2>

@Html.DropDownList("CopaList", ViewBag.copalistano as SelectList, "Selecione o ano")
    
asked by anonymous 28.04.2018 / 02:00

1 answer

0

If you want to display an on-screen message to the user stating what item he chose, there is no need to again interact with the database. the following example will only be with javascript

First, add a span element to the desired location with a id ,

<span id="msg"></span>

After that, in the scripts area, add the following code

<script type="text/javascript">     
    function exibeMensagemItemSelecionado(){
            myDropDown = document.getElementById("CopaList")
            document.getElementById("msg").innerHTML = "Você escolheu a opção "+  myDropDown.options[myDropDown.selectedIndex].text
        } 
</script>

Change your DropDownList by adding the function in the change event of it

@Html.DropDownList("CopaList", (SelectList)ViewBag.Anos, "Selecione o ano", new { @onchange="exibeMensagemItemSelecionado()"})

Explanation:

DropDownList do seu DropDownList uma DropDownList , nessa function pegamos o elemento function e atribuímos o texto desejado mais o texto selecionado do DropDownList . o DropDownList irá ter o DropDownList%

I left the code (Updated) on .NET Fiddle

    
28.04.2018 / 02:51