CodeGo.net>如何将剃刀视图模式属性值传递给JavaScript函数

我尝试将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,但是我有相同的结果:未定义

解决方法:

之所以变得未定义(假设值是一个字符串),是因为您需要将@ 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);
      }
  });

});
上一篇:春天 – 用Thymeleaf扩展视图


下一篇:javascript – 未捕获的SyntaxError:无效或意外的令牌