How to do an Event Change in ASP.NET Core MVC?

0

In ASP.NET we have the Event Change direct on Code Be-hind

 protected void ddlCiclo_SelectedIndexChanged(object sender, EventArgs e)
    {
         //algo aqui
    }

What would be the equivalent of ASP.NET Core MVC for a DropDownList ?

    
asked by anonymous 23.07.2018 / 19:33

1 answer

1

It is difficult to compare two paradigms so different: Web Forms x MVC.

Just to illustrate, see the treatment flow for an event in ASP.NET WebForms and ASP.NET MVC: ImageSource: Slide share: Mvc presentation

In your specific case, you handle the event of modifying a value in a drop-down list.

The ASP.NET MVC visual interface is composed of HTML + JavaScript + CSS (remembering that MVC is an architecture standard that can be applied outside the WEB scope)

In the case of a drop-down list, you can do this: Imagine you need a list with the birth year of the user, and in the selection you need to do something 1 - First you need a template (the M of MVC)

public class AnosModel
{
    public string anoNasc{get;set;}

    public List<SelectListItem> listaAnos() // simular um repositório. Eu sei que isso deveria estar em outra camada, mas por motivos de simplificação eu coloquei aqui.
    {
       List<SelectListItem> anos= new List<SelectListItem>()
        {
            new SelectListItem { Text = "1970", Value = "1" },
            new SelectListItem { Text = "1971", Value = "2" },
            new SelectListItem { Text = "1972", Value = "3" },
            new SelectListItem { Text = "1973", Value = "4" },
            new SelectListItem { Text = "1974", Value = "5" },
            new SelectListItem { Text = "1975", Value = "6" }

        };
        return anos;
    }
 }

2 - We created the View (MVC V in this example I will omit the complete creation of the view and focus on the construction of the drop down list)

    @Html.DropDownListFor(model => model.AnoNasc,  (IEnumerable<SelectListItem>)ViewBag.Anos, 
        new { onchange = "modificado(@Model.AnosNasc)" })

<script>
    function modificado(ano) {
        // fazer algo aqui. Você pode inclusive fazer uma chamada ao controller usando um dos verbos REST (GET, PUT, POST, DELETE, etc..)
        if (ano<"1974") {
          alert("Você é velho!");
       }
       else
       {
         alert("Você é jovem!");
       }
    }
</script>

3 - And the controller (the MVC C)

 public ActionResult Formulario1()
    {
        List<SelectListItem> anos = listaAnos();
        ViewBag.Anos = anos;// a passgem da lista é feita por ViewBag
        AnosModel modelo=new AnosModel();
        return View(modelo);
    }

This is a very simplified scenario, but it serves to illustrate the paradigm difference

    
23.07.2018 / 20:44