How to pass a razor view modal property value to a javascript function

前端 未结 1 1142
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 16:45

i try to send razor value to jquery funcion.

View:

@Html.TextBoxFor(model => model.NumTransportado, new { @class = \"form-control input-sm\", id = \"         


        
1条回答
  •  隐瞒了意图╮
    2021-01-23 17:01

    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.

    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; attach an event instead and make use of data-* attributes to store element specific values, this way you separate out html and js:

    i.e:

    @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);
          }
      });
    
    });
    

    0 讨论(0)
提交回复
热议问题