erbsoftware
erbsoftware

Reputation: 365

Set 'HiddenFor' value to the selected dropdown list value

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`

Upvotes: 0

Views: 2760

Answers (2)

Brian Mains
Brian Mains

Reputation: 50728

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.

Upvotes: 0

Cristian Szpisjak
Cristian Szpisjak

Reputation: 2479

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>

Upvotes: 1

Related Questions