Pavel
Pavel

Reputation: 766

MVC Core DropDownList selected value ignored

I am trying to access my page at: https://localhost:44319/Analyze/Index/6

The problem is that my drop down list always selects the first item in the list instead of the one provided by ID. While stepping through the debugger, before the View() is returned, I see that the SelectList was populated correctly.

AnalyzeController.cs

public IActionResult Index(int? Id)
{
    return Index(Id ?? getStatementEndingById(Id).StatementEndingId);
}

[HttpPost]
public IActionResult Index(int StatementEndingId)
{
    var statementEnding = getStatementEndingById(StatementEndingId);

    ViewBag.StatementEndingId = new SelectList(
                  _context.StatementEnding.OrderByDescending(s => s.StatementEndingId), 
                  "StatementEndingId", 
                  "Name", 
                  statementEnding);

    return View(getPayments(statementEnding));
}

private StatementEnding getStatementEndingById(int? statementEndingId)
{
    StatementEnding statementEnding;
    if (statementEndingId.HasValue)
    {
        statementEnding = _context.StatementEnding.FirstOrDefault(s => s.StatementEndingId == statementEndingId);
    }
    else
    {
        statementEnding = _context.StatementEnding.OrderByDescending(s => s.StatementEndingId).FirstOrDefault();
    }

    return statementEnding;
}

Setting DropDownList in Razor

@Html.DropDownList("StatementEndingId", null, new { @class = "form-control mb-2 mr-sm-2" })

I am using ASP.NET Core 2.1.

Any suggestions are much appreciated. Thanks in advance.

Upvotes: 1

Views: 1103

Answers (1)

Ivan Valadares
Ivan Valadares

Reputation: 949

First i would recomend to create a typed model, something like this one :

public class StatementViewModel
{
    public int StatementEndingId { get; set; }
    public List<SelectListItem> StatementEndings { get; set; }
}

Second fill the Model with all dropdown options (StatementEndings) and the selected one (StatementEndingId)

public IActionResult Index()
{
   var model = new StatementViewModel();
   model.StatementEndingId = getStatementEndingById(Id).StatementEndingId;
   model.StatementEndings = _context.StatementEnding.OrderByDescending(s => s.StatementEndingId).Select(p => new SelectListItem() { Text = p.Name, Value = p.StatementEndingId }).ToList();
   return View(model);
 }

And for the last, in the view

@model StatementViewModel
@Html.DropDownListFor(m => m.StatementEndingId, Model.StatementEndings, null, new { @class = "form-control mb-2 mr-sm-2" })

Upvotes: 3

Related Questions