我尝试将razor值发送给jquery funcion。
查看:
@Html.TextBoxFor(model => model.NumTransportado, new { @class = "form-control input-sm", id = "NumTransResp" + Model.ServicosID + "", name = "NumTransResp" + Model.ServicosID + "", onchange = "PreencheDadosVendedor(this, 3, " + @Model.ServicosID + ")" })
我可以使用除" + @Model.ServicosID + "
Js文件:
function PreencheDadosVendedor(idVend, tipoFuncionario, idServicoEdicao) {
$.getJSON("/Contrato/getDadosVendedor", { id: $(idVend).val(), tipoFuncionario: tipoFuncionario },
function (result) {
switch (tipoFuncionario) {
case 1:
$("#NomeVendedor_Contrato").val(result.NomeVendedor);
case 2:
$("#NomeTransResponsavel").val(result.NomeVendedor);
case 3:
$("#NomeTransResponsavel_" + idServicoEdicao + "").val(result.NomeVendedor);
}
});
}
我尝试idSericoEdicao
是我的@Model.ServicosID
,但我有相同的结果:未分解
答案 0 :(得分:5)
您未定义的原因(假设值是一个字符串)是因为您需要将@Model.ServicosID
包装在引号中,否则它将查找该属性的值作为变量的名称,而不是您只需要将值作为字符串传递。
试试这个: -
@Html.TextBoxFor(model => model.NumTransportado,
new { @class = "form-control input-sm",
id = "NumTransResp" + Model.ServicosID + "",
name = "NumTransResp" + Model.ServicosID + "",
onchange = "PreencheDadosVendedor(this, 3, '" + @Model.ServicosID + "')" });
^____ ^____
或者更好地执行此操作,而不是添加onchange
属性;添加事件并使用data-*
属性来存储元素特定值,这样就可以分离出html和js:
即:
@Html.TextBoxFor(model => model.NumTransportado,
new { @class = "form-control input-sm myclass", //Add a class
id = "NumTransResp" + Model.ServicosID + "",
data_tipoFuncionario = 3, //Add a data attribute
name = "NumTransResp" + Model.ServicosID + ""});
和
$('.myclass').change(function(e){
var idServicoEdicao = this.id.replace("NumTransResp",""), //get the part from its own id
tipoFuncionario = $(this).data("tipoFuncionario"); //get the value from data attribute
$.getJSON("/Contrato/getDadosVendedor", { id: this.value, tipoFuncionario: tipoFuncionario },
function (result) {
switch (tipoFuncionario) {
case 1:
$("#NomeVendedor_Contrato").val(result.NomeVendedor);
case 2:
$("#NomeTransResponsavel").val(result.NomeVendedor);
case 3:
$("#NomeTransResponsavel_" + idServicoEdicao).val(result.NomeVendedor);
}
});
});