I have this dropdown list for a Model’s property (Currency) in my View to which I have associated a JavaScript onchange function.
The goal of such function is to update some other field’s (Rate) value according to a Dictionary property from the model (which maps Currencies to their Rate).
<td>
@Html.DropDownListFor(model => model.Currency, new SelectList(ViewBag.CurrencyList, "Code", "Code"), new {onchange="update(this)"})
@Html.ValidationMessageFor(model => model.Currency)
<script type="text/javascript">
function update(elem) {
// alert("Currency changed!")
document.getElementById("@Html.IdFor(model => model.Rate)").value = '@Model.Currencies[<I_WISH_I_COULD_PUT_A_JS_VARIABLE_IN_HERE>]'
}
</script>
</td>
I want that “I_WISH_I_COULD_PUT_A_JS_VARIABLE_IN_HERE” to be elem.value, but I get a syntax error as the JS variable is interpreted as a literal.
I can’t seem to call an HTML helper with a Javascript value in it.
My goal is to update an EditorFor field according to the value selected in the combo box. but probably there’s something wrong with my approach?
Any help would be appreciated.
As I said in my comment, my approach didn’t make sense at all as I was mixing server-side code with client-side.
I used ajax inside my function update(elem) to retrieve the correct value and update the correspondent field:
I hope this might help someone in the future. Cheers.