Message appears when selecting value in a dropdownlist

Asked

Viewed 114 times

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 values of db is selected.

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

Follows 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")

1 answer

0

If you want to display a message on the screen to the user stating which item he has chosen, there is no need to again perform interaction with the database. the following example will be with javascript

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

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

After that, in the area of scripts, 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 adding to function at the event change his

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

Explanation:

Added to change eventdo seuDropdownlistumaFunction, nessaFunctionpegamos o elementospane atribuímos o texto desejado mais o texto selecionado doDropdownlist. oDropdownlistirá ter oID**CopaList**, pois é o primeiro parâmetro passado noDropdownlist`

I left the code (Updated) on .NET Fiddle

  • It still doesn’t work, I didn’t think to use jquery and I didn’t find how to put the id in select

  • @bcastro1995, asks the question the code of its View, please, after that I will edit the question with javascript only

  • @bcastro1995 updated with javascript

Browser other questions tagged

You are not signed in. Login or sign up in order to post.