[英]How to pass a razor view modal property value to a javascript function
i try to send razor value to jquery funcion. 我尝试将razor值发送到jquery funcion。
View: 视图:
@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 + ")" })
i can use all parameters except " + @Model.ServicosID + "
我可以使用除
" + @Model.ServicosID + "
以外的所有参数
Js file: 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);
}
});
}
i try to do idSericoEdicao
is my @Model.ServicosID
, but i have same result: undifined 我尝试做
idSericoEdicao
是我的@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. 之所以变得未定义(假设值是一个字符串),是因为您需要将
@Model.ServicosID
括在引号中,否则它将寻找属性的值作为变量的名称,而只需要传递字符串形式的值。
Try this:- 尝试这个:-
@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 + "')" });
^____ ^____
Or better do this, instead of adding an onchange
attribute; 或者最好这样做,而不是添加
onchange
属性。 attach an event instead and make use of data-*
attributes to store element specific values, this way you separate out html and js: 而是附加一个事件,并利用
data-*
属性存储元素特定的值,这样您就可以将html和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 + ""});
and 和
$('.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);
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.