Set 'HiddenFor' value to the selected dropdown list value

2.5k Views Asked by At

I have the following dropdownlist:

@Html.DropDownListFor(m => m.SelectedOrderCodeId, new SelectList(Model.OrderCodesList, "OrderCodeId", "DisplayString"))

Now the OrderCodesListhas the following: OrderCodeId,DisplayString & Percentage

How can I set a HiddenFor value to the Percentage of the value selected from that dropdownlist? (Below code has to be complete according to pseudo cause I'm not sure what to do next - if it is even possible).

@Html.HiddenFor(m => m.FinancialSupportPercentage, new { @Value = Model.OrderCodesList.Where

pseudo:

OrderCodesList.Select 'Percentage' 
 Where
    'OrderCodeId'
 is the `Selected 'OrderCodeId` from the `DropDownListFor`
2

There are 2 best solutions below

0
Cristian Szpisjak On

Here is a simple way:

Class

public class Order
{
    public int OrderCodeId { get; set; }
    public string DisplayString { get; set; }
    public int Percentage { get; set; }
}

Controller

public JsonResult GetPercentage(int OrderCodeId)
{
    var data = _dbContext.List
        .FirstOrDefault(p => p.OrderCodeId == OrderCodeId)
        .Percentage;

    return Json(data, JsonRequestBehaviour.AllowGet);
}

View

@Html.DropDownListFor(m => m.SelectedOrderCodeId, new SelectList(Model.OrderCodesList, "OrderCodeId", "DisplayString"))
@Html.HiddenFor(m => m.FinancialSupportPercentage)

<scripts>
    $('#SelectedOrderCodeId').on('change', function () {
        var selectedIndex = $(this).val();

         $.ajax({
             url: '/ControllerName/GetPercentage',
             data: { OrderCodeId: selectedIndex },
             method: 'GET',
             success: function (result) {
                 $('FinancialSupportPercentage').val(result);
             }
        });
    });
</scripts>
2
Brian Mains On

Sounds like you may want something on client-side JavaScript. The server-side code I think you want is:

@{
  var entity =  Model.OrderCodesList.FirstOrDefault(i => i.OrderCodeId == Model.SelectedOrderCodeId);
  double percentage = 0;

  if (entity != null { percentage = entity.Percentage }
} 

@Html.Hidden("FinancialSupportPercentage", percentage)

I used hidden as it gives you direct access to the value; HiddenFor usually extracts the value from the model.

The above approach works well if you were doing everything on the server, and if that is the case, then this will work fine. But if the user changes the dropdown, do you want the hidden to change? If you do, you need javascript.