Select Tag Helper ASP .NET CORE 2.0 is not setting selected value

4.5k views Asked by At

I am trying to use select tag helper in ASP .NET Core 2.0 MVC application according to this thread Select Tag Helper in ASP.NET Core MVC .

Here is my view model :

public class SensorEditViewModel
{
    public int SensorID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Uid { get; set; }
    public string AE_SN { get; set; }
    public DateTime SubscriptionEndDate { get; set; }
    public string Type { get; set; }
    public bool sensorAccessApproved { get; set; }

    public string UserId { get; set; }
    public SelectList UserEmailList { get; set; }
}

Here is part of GET where model is filled with propper SelectList and UserId and pushed to the view:

var users = _context.Users.OrderBy(u => u.UserName).Select(x => new { Text = x.Email, Value = x.Id });
model.UserEmailList = new SelectList(users, "Value", "Text");
model.Id = ownerId;

return View(model);

and finally in the Edit view I am using Select TagHelper like this :

<div class="form-group">
    <label class="control-label">User Email</label>
    <select asp-for="Id" asp-items="@Model.UserEmailList" class="form-control" ></select>
</div>

But my problem is that Select is not preset with value selected in controller (model.Id = ownerId;). Do you have any clue what might be wrong? Thanks.

1

There are 1 answers

0
ChrisR On

You need to pass the selected value into the SelectList constructor:

model.UserEmailList = new SelectList(users, "Value", "Text", ownerId)

More info in the MS docs