using selectedValue from DropDownList

0

Working with ASP.NET Core 1.1 Visual Studio 2017 - EntityFramework 1.0.0, Microsoft .Net Framework 4.7.02046, SQL Server 2012 LocalDB C #
I am making my first experience with these tools. I follow the example ContosoUniversity developed in the MS documentation.
I have read and tried many queries without finding the solution to the following problem: I want to recover and use the selectedValue of a DropDownList.

Model

    public class Rol
{
    public int RolID { get; set; }
    public string EnRol { get; set; }
 …


}

Controller

var rolQuery = from r in _context.Roles
                           orderby r.RolID
                           select r;
var ListaDesplegableRoles = new SelectList(rolQuery.AsNoTracking(),
                "RolID",
                "EnRol",
                elegidoRol);
ViewBag.RolId = ListaDesplegableRoles;  

View

div class="form-group">
        <label class="col-md-2 control-label">En rol de:</label>
        <div class="col-md-10">
            <select name="eR" class="form-control" asp-items="ViewBag.RolId"  >
                <option value="">-elegir rol--</option>
            </select>
        </div>
</div>

Up to here it works perfect.

When I pass the DropDownList from the Model, I have no problems. In this case that I pass through ViewBag I can not find the way to retrieve the selectedvalue to use it in another action (Post).

I would also like to know what documentation or book to read (I have several downloaded from MS docs and also a book about C #)
Thanks.

    
asked by María Celia Ibarra 12.12.2017 в 23:08
source

1 answer

0

Maria the problem is that your select works well at the time of showing but when you pass the parameters to a post-type action the role does not arrive because you have defined name="eR" and your method may expect a RolID. Try changing the name of the parameter you pick in the select.

<select name="RolID" class="form-control" asp-items="ViewBag.RolId"  >
            <option value="">-elegir rol--</option></select>

I also recommend this way to pick up the list in your controller that is better optimized.

ViewData["RolId"] = new SelectList(_context.Roles.OrderBy(r => r.RolID), "RolID", "EnRol");
    
answered by 13.12.2017 в 19:15