Ferdi
Ferdi

Reputation: 61

Select tag helper selected value not rendered in view

I need some help with my select tag helper.

I have an asp.net MVC View with a select 2 control as follows:

<div class="col-md-3">
     <div class="form-group">
         <label asp-for="NumberingType.Type" class="control-label" data-toggle="popover" data-placement="right" data-trigger="click" title="Field Help" data-content="Select the Numbering Scheme type that you want to create">Number Scheme Type *</label>
               <select asp-for="NumberingType.TenantNumberingTypeId" asp-items="Model.NumberingType.NumberingTypeList" class="form-control select2">
                    <option></option>
                </select>
          <span asp-validation-for="NumberingType.TenantNumberingTypeId" class="text-danger"></span>
     </div>
</div>

I am initialising the select2 as follows:

<script type="text/javascript">
    $(document).ready(function () {

        $(".select2").select2({
            placeholder: "Select",
            theme: 'bootstrap',
            allowClear: true
        });
    });
</script>

I am loading the correct scripts:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>

In my controller, I am populating the select 2 as follows:

public async Task<IActionResult> EditNumberScheme(int numberId)
{
   var vm = new NumberingViewModel();

   try
   {
      vm = await GetNumberingViewModel(numberId);
      vm = UpdatedBaseViewModel<NumberingViewModel>(vm);
   }
   catch (Exception e)
   {
       await ErrorHandler.HandleException(e);

       vm.MessageType = BaseViewModel.UserMessageType.Error;
    }
    return View(vm);
}

and

private async Task<NumberingViewModel> GetNumberingViewModel(int numberId)
{
    var number = await DataGet.GetTenantNumberScheme(numberId);

     NumberingViewModel model = new NumberingViewModel
     {
          Numbering = number
     };

     model.NumberingType = new TenantNumberingTypeModel();
     model.NumberingType.NumberingTypeList = DataGet.GetTenantNumberingTypes().Result
                    .Select(x => new SelectListItem { Value = x.TenantNumberingTypeId.ToString(), Text = x.Type, Selected = (x.TenantNumberingTypeId == number.TenantNumberingTypeId) })
                    .ToList();

       model.Owner = await DataGet.GetTenantOwner(UserInfo.Instance.Tenant.TenantId);

       return model;
}

The select2 values are successfully loaded from the database and the selected value shows in the controller.

When placing a breakpoint at the select in the View, it is clear that the selected value is set as true in the NumberingTypeList.

Model.NumberingType.NumberTypeList = Count = 4
[1] = {Microsoft.AspNetCore.Mvc.Rendering.SelectListItem}
Disabled = false
Group = null
Selected = true
Text = "Credit Note"
Value = "2"

However the selected value is not rendered in the view.

<select class="form-control select2 select2-hidden-accessible" data-val="true" data-val-required="The TenantNumberingTypeId field is required." id="NumberingType_TenantNumberingTypeId" name="NumberingType.TenantNumberingTypeId" tabindex="-1" aria-hidden="true">
<option></option>
<option value="1">Invoice</option>
<option value="2">Credit Note</option>
<option value="3">Order</option>
<option value="4">Deposit</option>
</select>

Any help will be appreciated

Thanks

Upvotes: 1

Views: 1573

Answers (2)

Ferdi
Ferdi

Reputation: 61

I managed to get this working by following this tutorial https://www.learnrazorpages.com/razor-pages/tag-helpers/select-tag-helper

It seems that the error is caused by the binding of the asp-for attribute. When I explicitly set the selected item in the controller as so:

model.NumberType = new TenantNumberingTypeModel();
model.NumberType.NumberSchemeList = DataGet.GetTenantNumberingTypes().Result
    .Select(x => new SelectListItem { Value = x.TenantNumberingTypeId.ToString(), Text = x.Type })
    .ToList();

model.NumberingType.TenantNumberingTypeId = number.TenantNumberingTypeId;

number being the object retrieved from the database

then it works correctly and the asp-items automatically selects the value that is represented by the asp-for attribute.

<select class="form-control select2 select2-hidden-accessible" data-val="true" data-val-required="Please select a type" id="NumberType_NumberTypeId" name="NumberType.NumberTypeId" tabindex="-1" aria-hidden="true">
<option></option>
<option value="1">Invoice</option>
<option selected="selected" value="2">Credit Note</option>
<option value="3">Order</option>
<option value="4">Deposit</option>
</select>

Hope this helps someone

Upvotes: 2

Ceren &#246;zdemir
Ceren &#246;zdemir

Reputation: 21

That is the example of the visibility, you must use "select2.full.min.js".

Upvotes: 0

Related Questions