简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM