我有一个编辑器模板,其中包含一个表格行与(除其他外)一个下拉/组合框,以选择货币。此编辑模板在同一个View上显示多次,用户可以根据需要多次添加这些行。
我希望行的下拉列表中的更改反映在同一行的EditorFor (货币汇率)中,因此我添加了一个onchange html参数:
<td>
@*@Html.LabelFor(model => model.Currency)*@
@Html.DropDownListFor(model => model.Currency, new SelectList(Model.CurrencyList, "Code", "Code"), new { onchange = "updateCurrency(this)" })
@Html.ValidationMessageFor(model => model.Currency)
</td>我的javascript函数调用ajax来检索所选货币的汇率:
function updateCurrency(elem) {
alert("Currency changed!")
$.ajax({
type: "GET",
url: "Currency?code=" + elem.value,
success: function (msg) {
// The Rate field's Id:
var RateId = "@Html.ClientIdFor(model=>model.Rate)" // // Halp, problem is here!
document.getElementById(RateId).value = msg;
}
});
}我的问题是
var RateId = "@Html.ClientIdFor(model=>model.Rate)"具有Html帮助器,它是服务器端代码。因此,当我查看页面的源代码时,javascript代码被复制(每行一次),并且所有的变量RateId = "@Html.ClientIdFor(model=>model.Rate)“都指向最近添加的列的EditorFor。
也许我尝试解决问题的方法是错误的,但是我如何让我的javascript代码更新所需的字段(即与更改的下拉列表在同一行中的字段)。
我认为其中一个问题是我在编辑器模板上有javasript,但是如果我这样做,我如何访问像document.getElementById(RateId).value = msg;这样的东西呢?
提前感谢:)
发布于 2013-01-23 17:16:12
我想通了。希望它能帮助到某人:
在我看来:
@Html.DropDownListFor(model => model.Currency, new SelectList(Model.CurrencyList, "Code", "Code"), new { @onchange = "updateCurrency(this, " + @Html.IdFor(m => m.Rate) + ", " + @Html.IdFor(m => m.Amount) + ", " + @Html.IdFor(m => m.Total) + ")" })在一个单独的JavaScript文件中:
function updateCurrency(elem, RateId, AmountId, TotalId) {
var cell = elem.parentNode // to get the <td> where the dropdown was
var index = rowindex(cell) // get the row number
// Request the currency's rate:
$.ajax({
blah blah blah .........
(RateId[index - 1]).value = 'retreived value'; // Set the rate field value.
});
}到目前为止似乎还行得通。
https://stackoverflow.com/questions/14404174
复制相似问题