Create a dropdownlist and grab the selected id Asp.net MVC

2

I need to create a Dropdownlist at run time with 2 options to choose from. With this, I need to do a check by picking the selected record and then accessing that method. This is after clicking a ActionLink .

How do I set an id for this dropdownlist to tweak it? How can I do this?

So far I've done this:

<td>
    @Html.DropDownListFor(modelItem => item.EscolhaBanco, new SelectList(new List<Object>
    {
         new {value = 0, text = ""},
         new {value = 1, text = "Bradesco"},
         new {value = 2, text = "Santander"}
    }, "value", "text", 0))
</td>

 <td>@Html.ActionLink("Imprimir", "ImprimirBoleto", new { Fatura = item.NumeroDocumento }, new { target = "_blank" })</td>
    
asked by anonymous 10.08.2015 / 14:50

1 answer

1

Define an anonymous object in the HtmlAttributes argument as follows:

@Html.DropDownListFor(modelItem => item.EscolhaBanco, new SelectList(new List<Object>
{
     new {value = 0, text = ""},
     new {value = 1, text = "Bradesco"},
     new {value = 2, text = "Santander"}
}, new { id = "IdDoMeuDropDownList" }))

EDIT

To pass the selected value to the Controller , you will have to use a <button> instead of a ActionLink . It would look like this:

@using (Html.BeginForm()) 
{
    <td>
        @Html.DropDownListFor(modelItem => item.EscolhaBanco, new SelectList(new List<Object>
    {
        new {value = 0, text = ""},
        new {value = 1, text = "Bradesco"},
        new {value = 2, text = "Santander"}
    }, "value", "text", 0))
    </td>

    <input type="submit" value="Enviar" class="btn btn-default" />
}

I do not know if you have defined a ViewModel for this, but the correct one is to set the ViewModel and make View / p>

namespace MeuProjeto.ViewModels
{
    public class EscolhaBancoViewModel 
    {
        public int EscolhaBanco { get; set; }
    }
}

View looks like this:

@model MeuProjeto.ViewModels.EscolhaBancoViewModel

@using (Html.BeginForm()) 
{
    <td>
        @Html.DropDownListFor(modelItem => item.EscolhaBanco, new SelectList(new List<Object>
    {
        new {value = 0, text = ""},
        new {value = 1, text = "Bradesco"},
        new {value = 2, text = "Santander"}
    }, "value", "text", 0))
    </td>

    <input type="submit" value="Enviar" class="btn btn-default" />
}

And Controller :

public ActionResult MinhaAction(EscolhaBancoViewModel viewModel) 
{
    // O valor vai aparecer em viewModel.EscolhaBanco
}
    
10.08.2015 / 16:16