如何将剃刀视图模态属性值传递给javascript函数 [英] How to pass a razor view modal property value to a javascript function
问题描述
我尝试将razor值发送给jquery funcion。
i try to send razor value to 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 file:
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
,但我有相同的结果:undifined
i try to do idSericoEdicao
is my @Model.ServicosID
, but i have same result: undifined
推荐答案
你未定义的原因(假设值是一个字符串)是因为你需要在引号中包装 @ Model.ServicosID
,否则它将寻找作为变量名称的属性值,而只需要将值作为字符串传递。
The reason you are getting undefined (Assuming value is a string) is because you need to wrap @Model.ServicosID
it in quotes, otherwise it will look for the value of the property as the name of the variable, instead you just need to pass the value as the a string.
试试这个: -
@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:
Or better do this, instead of adding an onchange
attribute; attach an event instead and make use of data-*
attributes to store element specific values, this way you separate out html and js:
ie:
@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);
}
});
});
这篇关于如何将剃刀视图模态属性值传递给javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!