get value from @ Html.DropDownList in actionresult through formcollection MVC

-1

I have an @Html.DropDownList that I filled with a List List with data already defined, the dropdown list is inside a form that is sent to the SaveConfiguration controller, I retrieve the data as a parameter to the FormCollection form controller but I could not retrieve the value that was selected (text of the selected option) in the controller, if I do it in the form var ValueDos = form ["source"] ;, I get the index that the dropdownlist gives to each option of the ddl

            <div class="text-left col-md-4">
                <label class="col-sm-12 control-label" for="email-03">Tipo de fuente:</label>
                @Html.DropDownList("fuente", ViewBag.TiposFuente as SelectList, new { @class = "form-control", id = "TipoFuente", name = "TipoFuente" })                                    
                <br />
            </div>

action result

    [HttpPost]
    public ActionResult GuardarConfiguracion(FormCollection form)
    {

        List<clsTipoFuente> LstTiposFuente;
        LstTiposFuente = new List<clsTipoFuente>();
        clsTipoFuente TipoFuenteArial = new clsTipoFuente()
        {
            IdTipoFuente = 1,
            TipoFuente = "Arial",
        };
        LstTiposFuente.Add(TipoFuenteArial);
        clsTipoFuente TipoFuenteCalibri = new clsTipoFuente()
        {
            IdTipoFuente = 3,
            TipoFuente = "Calibri",
        };
        LstTiposFuente.Add(TipoFuenteCalibri);
        clsTipoFuente TipoFuenteTimes = new clsTipoFuente()
        {
            IdTipoFuente = 5,
            TipoFuente = "Times",
        };
        LstTiposFuente.Add(TipoFuenteTimes);

        ViewBag.TiposFuente = new SelectList(LstTiposFuente, "IdTipoFuente", "TipoFuente");


        var ValorUno = form["txtNombreLicitacion"];
        var ValorDos = form["fuente"];


        return View("Index");

    }
    
asked by Ivxn 22.03.2018 в 19:30
source

2 answers

1

As ViewBag.Fuentes is of type SelectList , then at the moment of filling SelectList , assign the value you want the server to receive.

For example, when you generate the SelectList , the SelectListItem you specify the text (what you want) to the property Value and not the index (or whatever you are assigned to it) .:

var item = new SelectListItem{ 

Text="The Text", Value =

answered by 22.03.2018 в 19:49
0

Remove the 'id' and the 'name' from the htmlAttributes, with that you are renaming your html select-option element, then in your form they come with that name:

<div class="text-left col-md-4">
    <label class="col-sm-12 control-label" for="email-03">Tipo de fuente:</label>
    @Html.DropDownList("fuente", ViewBag.TiposFuente as SelectList, new { @class = "form-control" })
    <br />
</div>

Or, in your action method, read them with that name:

var ValorDos = form["TipoFuente"];
    
answered by 22.03.2018 в 21:26