Jump to content

wrb

Members
  • Posts

    40
  • Joined

  • Last visited

Posts posted by wrb

  1. Anyone have any suggestions?
    In the code below returns with error when taking delete a table record:
    SCRIPT:
    $("#add").click(function () {
    $.ajax({
    url: '@Url.Action("AddProduto", "Produto")',
    type: "POST",
    data: $('#formprod').serializeArray(),
    success: function (data) {
    if (data.success) {
    $('#tabelaproduto > tbody:last').append('<tr style="font-size:10px">' + '<td hidden>' + data.id + '</td>' + '<td>' + data.descricao + '</td>' + '<td>' + '<input type="image" src="/Images/excluir.png" onclick="clicado(this)">' + '</td>' + '</tr>');
    $('#formprod')[0].reset();
    $("#validacaoproduto").html("");
    }
    else {
    $("#validacaoproduto").html(data.msg);
    }
    }
    });
    return false;
    });
    function clicado(a) {
    console.log($(a).closest('tr')[0].rowIndex);
    var linhaIndex = $(a).closest('tr')[0].rowIndex;
    var codigo = $(a).closest('tr').children('td')[0].innerText;
    $.ajax({
    url: '@Url.Action("DelProduto", "Produto")',
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    data: { codigo: codigo },
    success: function (data) {
    document.getElementById("tabelaproduto").deleteRow(linhaIndex);
    console.log("ok");
    }
    });
    }
    ERROR:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Invalid JSON primitive: codigo.</title>
    <meta name="viewport" content="width=device-width" />
    <style>
    body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
    p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
    b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
    H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
    H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
    pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
    .marker {font-weight: bold; color: black;text-decoration: none;}
    .version {color: gray;}
    .error {margin-bottom: 10px;}
    .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
    @media screen and (max-width: 639px) {
    pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
    }
    @media screen and (max-width: 479px) {
    pre { width: 280px; }
    }
    </style>
    </head>
    <body bgcolor="white">
    <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
    <h2> <i>Invalid JSON primitive: codigo.</i> </h2></span>
    <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
    <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    <br><br>
    <b> Exception Details: </b>System.ArgumentException: Invalid JSON primitive: codigo.<br><br>
    <b>Source Error:</b> <br><br>
    <table width=100% bgcolor="#ffffcc">
    <tr>
    <td>
    <code>
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
    </td>
    </tr>
    </table>
    <br>
    <b>Stack Trace:</b> <br><br>
    <table width=100% bgcolor="#ffffcc">
    <tr>
    <td>
    <code><pre>
    [ArgumentException: Invalid JSON primitive: codigo.]

     

  2. Anyone have any suggestions?
    In the code below returns with error when taking delete a table record:
    SCRIPT:
    $("#add").click(function () {
    $.ajax({
    url: '@Url.Action("AddProduto", "Produto")',
    type: "POST",
    data: $('#formprod').serializeArray(),
    success: function (data) {
    if (data.success) {
    $('#tabelaproduto > tbody:last').append('<tr style="font-size:10px">' + '<td hidden>' + data.id + '</td>' + '<td>' + data.descricao + '</td>' + '<td>' + '<input type="image" src="/Images/excluir.png" onclick="clicado(this)">' + '</td>' + '</tr>');
    $('#formprod')[0].reset();
    $("#validacaoproduto").html("");
    }
    else {
    $("#validacaoproduto").html(data.msg);
    }
    }
    });
    return false;
    });
    function clicado(a) {
    console.log($(a).closest('tr')[0].rowIndex);
    var linhaIndex = $(a).closest('tr')[0].rowIndex;
    var codigo = $(a).closest('tr').children('td')[0].innerText;
    $.ajax({
    url: '@Url.Action("DelProduto", "Produto")',
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    data: { codigo: codigo },
    success: function (data) {
    document.getElementById("tabelaproduto").deleteRow(linhaIndex);
    console.log("ok");
    }
    });
    }
    ERROR:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Invalid JSON primitive: codigo.</title>
    <meta name="viewport" content="width=device-width" />
    <style>
    body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
    p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
    b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
    H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
    H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
    pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
    .marker {font-weight: bold; color: black;text-decoration: none;}
    .version {color: gray;}
    .error {margin-bottom: 10px;}
    .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
    @media screen and (max-width: 639px) {
    pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
    }
    @media screen and (max-width: 479px) {
    pre { width: 280px; }
    }
    </style>
    </head>
    <body bgcolor="white">
    <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
    <h2> <i>Invalid JSON primitive: codigo.</i> </h2></span>
    <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
    <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    <br><br>
    <b> Exception Details: </b>System.ArgumentException: Invalid JSON primitive: codigo.<br><br>
    <b>Source Error:</b> <br><br>
    <table width=100% bgcolor="#ffffcc">
    <tr>
    <td>
    <code>
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
    </td>
    </tr>
    </table>
    <br>
    <b>Stack Trace:</b> <br><br>
    <table width=100% bgcolor="#ffffcc">
    <tr>
    <td>
    <code><pre>
    [ArgumentException: Invalid JSON primitive: codigo.]

     

  3. How can I make the DropDownList appear only item from a particular id = Med_Produto?

    Controller:
    ViewBag.cod_Med= new SelectList(db.Prod_Med, "id", "descricao");
    View:
    @Html.DropDownList("cod_Med", null, String.Empty, new { id = "Med_Produto", name = "cod_Med", @class = "form-control" })
    Example: id> 38
  4. Hi, how to calculate a percentage increase?
    I have 3 fields to when entering a value in the second the third returns with the result.
    I tried the code below, but nothing appears on preco2 field.
    <div class="editor-field col-md-7">
    @Html.TextBoxFor(model => model.preco1, new { id = "preco1", name = "preco1", @class = "form-control" })
    </div>
    <div class="editor-field col-md-7">
    @Html.TextBoxFor(model => model.percentual, new { id = "percentual", name="percentual", @class = "form-control", placeholder = "1.00" })
    </div>
    <div class="editor-field col-md-7">
    @Html.TextBoxFor(model => model.preco2, new { id = "preco2", name = "preco2", @class = "form-control" })
    </div>
    <script>
    $("#percentual").change(function () {
    preco= document.getElementById("#preco1").value;
    percent = document.getElementById("#percentual").value;
    document.getElementById("#preco2").innerHTML = preco * percent;
    });
    </script>
  5. See It. The graph is right, the URL this right. The problem is the event when the select receives a graphic value must render. In fact I do not know if the path is with the post code. Lack knowledge in JavaScript...

  6. I changed the code because I did not find the error ... The "onchange" sends the value and renders the chart. The URL is correct, it is the place of animals I put 1 for example, the chart is rendered.

  7. I was with an event in select "onchange" as below, but in the select has only one item I not I the desired effect.
    I need to render the chart being the select filled.
    <form action="">
    @Html.DropDownList("cod_animal", null, new { onchange = "drawchart(this.value)", Name = "cod_animal", id = "cod_animal", @class = "form-control" })
    </form>
    <script type="text/javascript">
    google.load('visualization', '1.1', { 'packages': ['corechart'] });
    google.setOnLoadCallback(function(){drawchart('')});
    function drawchart(cod_animal) {
    var url = '/Programa_Nutricao/Avaliacao/EvolucaoPeso/' + cod_animal;
    $.get(url, {},
    function (data) {
    var tdata = new google.visualization.DataTable();
    tdata.addColumn('date', 'data_semanal');
    tdata.addColumn('number', 'peso_kg');
    for (var i = 0; i < data.length; i++) {
    if (data.data_semanal != null)
    tdata.addRow([ToJavaScriptDate(data.data_semanal), parseFloat(data.peso_kg)]);
    }
    var options = {
    title: 'Evolução do peso corporal',
    width: 700,
    height: 500,
    vAxis: { title: "PESO (kg)", minValue: 1, maxValue: 6 },
    hAxis: { title: "DATA", textStyle: { fontSize: 10 } },
    legend: { position: "none" }
    };
    var chart = new google.visualization.LineChart(document.getElementById('EvolucaoPeso'));
    chart.draw(tdata, options);
    });
    }
    </script>
  8. In the code below I need to select an item in the "select" the graphic is rendered, how could implement this?

    @using (Html.BeginForm()){    @Html.AntiForgeryToken()    @Html.ValidationSummary(true)<select id="animais" name="cod_animal" class="form-control"></select><script type="text/javascript">        //google.load('visualization', '1.1', { 'packages': ['corechart'] });     //google.setOnLoadCallback(drawChart);    function drawChart() {              var frm = document.getElementById('#animais');        var animais = frm.options[frm.selectedIndex].value;                var url = '/Programa_Nutricao/Avaliacao/EvolucaoPeso/' + animais;        $.get(url, {},              function (data) {                  var tdata = new google.visualization.DataTable();                  tdata.addColumn('date', 'data_semanal');                  tdata.addColumn('number', 'peso_kg');                  for (var i = 0; i < data.length; i++) {                      if (data[i].data_semanal != null)                          tdata.addRow([ToJavaScriptDate(data[i].data_semanal), parseFloat(data[i].peso_kg)]);                  }                  var options = {                      title: 'Evolução do peso corporal',                      width: 700,                      height: 500,                      vAxis: { title: "PESO (kg)", minValue: 1, maxValue: 6 },                      hAxis: { title: "DATA", textStyle: { fontSize: 10 } },                      legend: { position: "none" }                  };                  var chart = new google.visualization.LineChart(document.getElementById('EvolucaoPeso'));                  chart.draw(tdata, options);              });    }</script> <div id="EvolucaoPeso" style="width: 900px; height: 500px;"></div>
  9. This is correct?

    <script type="text/javascript">
    google.load('visualization', '1.1', { 'packages': ['corechart'] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {
    var e = documento.getElementById("#animais");
    var animais = e.opções[e.selectedIndex].valor;
    var url = '/Programa_Nutricao/Avaliacao/EvolucaoPeso/' + animais;
  10. How could pass the value of a selected item in a select in the url below to replace the 1:

    <select id="animais" name="cod_animal" class="form-control"></select>
    <script type="text/javascript">
    google.load('visualization', '1.1', { 'packages': ['corechart'] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {

    var url = '/ Programa_Nutricao / Evaluation / EvolucaoPeso /' + 1;

  11. Sorted out:

     

    $("#cod_Prod_Med_Formula").change(function () {
    var dados = $(this).val().toString();
    var options = "";
    if (dados != 0) {
    $.ajax({
    url: '@Url.Action("RetornaPrincipio", "Medicamento_Produto")',
    type: 'POST',
    dataType: 'json',
    data: { codigo: dados },
    success: function (result) {
    $.each(result, function (key, val) {
    options += '<option value="' + val["cod_Principio_Ativo"] + '" selected>' + val["descricao"] + '</option>';
    });
    $("#cod_Principio_Ativo").html(options);
    }
    });
    } else {
    console.log(options)
    $("#cod_Principio_Ativo").html(options);
    }
    }).change();
  12. The error is on the line "var PrincipioID = $ (" # Formula_Existente ") val ();.." I select the item in the DropDownList id = "cod_Prod_Med_Formula" and return to "descricao" in the DropDownList id = "cod_Principio_Ativo". What should I change this code? What should I implement so that the words "'+ val [" id "] +'" returns with "cod_Principio_Ativo"?

     

    Following classes:

     public partial class Prod_Med_Produto    {        public Prod_Med_Produto()                    public int id { get; set; }        public Nullable<int> cod_Prod_Med_Formula { get; set; }        public string nome_comercial { get; set; }               public Nullable<int> cod_Principio_Ativo { get; set; }                   public virtual Prod_Med_Principio_Ativo Prod_Med_Principio_Ativo { get; set; }        public virtual Prod_Med_Produto_Formula Prod_Med_Produto_Formula { get; set; }          } public partial class Prod_Med_Produto_Formula    {        public Prod_Med_Produto_Formula()        {                       this.Prod_Med_Produto = new HashSet<Prod_Med_Produto>();        }            public int id { get; set; }        public string formula { get; set; }        public Nullable<int> cod_Principio_Ativo { get; set; }                  public virtual Prod_Med_Principio_Ativo Prod_Med_Principio_Ativo { get; set; }        public virtual ICollection<Prod_Med_Produto> Prod_Med_Produto { get; set; }           }
  13. Would anyone guide something for the error below?

    "The required anti-forgery form field "__RequestVerificationToken" is not present."

     

    The error occurs when trying to delete a row in the table on the button below:

    <button onclick="return false;">Excluir</button>
     $("#add").click(function () {        var token = $('[name=__RequestVerificationToken]').val();        $.ajax({            url: '@Url.Action("AddComponente", "Medicamento_formula")',            cache: false,            headers: { "__RequestVerificationToken": token },                       type: "POST",            data: $('#formcomp').serializeArray(),            success: function (data) {                if (data.success) {                    $('#tabelacomposicao > tbody:last').append('<tr>' + '<td hidden>' + data.id + '</td>' + '<td>' + data.descricao + '</td>' + '</td>' + '<td>' + data.excipiente + '</td>' + '<td>' + data.unidade_Medida + '</td>' + '<td>' + data.principio + '</td>' + '<td>' + data.quantidade + '</td>' + '<td>' + '<input type="image" src="/Images/excluir.png" onclick="clicado(this)">' + '</td>' + '</tr>');                    $('#formcomp')[0].reset();                    $("#validacaocomposicao").html("");                }                else {                    $("#validacaocomposicao").html(data.msg);                }            }        });        return false;    });    function clicado(a) {        var token = $('[name=__RequestVerificationToken]').val();        console.log($(a).closest('tr')[0].rowIndex);        var linhaIndex = $(a).closest('tr')[0].rowIndex;        var codigo = $(a).closest('tr').children('td')[0].innerText;                     $.ajax({            type: "POST",            url: '@Url.Action("DelComponente", "Medicamento_formula")',                       cache: false,            headers: { "__RequestVerificationToken": token },            contentType: 'application/json; charset=utf-8',            data: { codigo: codigo },            success: function (data) {                document.getElementById("tabelacomposicao").deleteRow(linhaIndex);                console.log("ok");            }        });    }

    CONTROLLER:

     [AttributeUsage(AttributeTargets.Class)]        public class ValidateAntiForgeryTokenOnAllPosts : AuthorizeAttribute        {            public override void OnAuthorization(AuthorizationContext filterContext)            {                var request = filterContext.HttpContext.Request;                //  Only validate POSTs                if (request.HttpMethod == WebRequestMethods.Http.Post)                {                    //  Ajax POSTs and normal form posts have to be treated differently when it comes                    //  to validating the AntiForgeryToken                    if (request.IsAjaxRequest())                    {                        var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];                        var cookieValue = antiForgeryCookie != null                            ? antiForgeryCookie.Value                            : null;                        AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);                    }                    else                    {                        new ValidateAntiForgeryTokenAttribute()                            .OnAuthorization(filterContext);                    }                }            }        }[HttpPost]        [ValidateAntiForgeryToken]        public ActionResult DelComponente(string codigo)        {            var _Codigo = Convert.ToInt32(codigo);            Composicao.Remove(_Codigo);            return Json(new { success = true });        }

    CREATE

    @using (Html.BeginForm("Create", "Medicamento_formula", FormMethod.Post, new { id = "formularioprincipal" })){     @Html.AntiForgeryToken()    @Html.ValidationSummary(true)} <table class="table table-hover table-bordered" id="tabelacomposicao">                            <thead>                                <tr style="font-size:10px">                                    <th>                                        <i> NOME</i>                                    </th>                                    <th>                                        <i> EXCIPIENTE</i>                                    </th>                                    <th>                                        <i> UNIDADE DE MEDIDA</i>                                    </th>                                    <th>                                        <i> PRINCIPIO ATIVO</i>                                    </th>                                    <th>                                        <i> QUANTIDADE</i>                                    </th>                                    <th>                                        <i>EXCLUIR</i>                                    </th>                                </tr>                            </thead>                            <tbody id="linhascomp">                                @foreach (var item in @ViewBag.ComposicaoFormula)                                {                                    <tr style="font-size:10px">                                        <td>                                            @item.descricao                                        </td>                                        <td>                                            @item.excipiente                                        </td>                                        <td>                                            @item.unidade_Medida                                        </td>                                        <td>                                            @ViewBag.PrincipioAtivo.Find(item.cod_Principio_Ativo).descricao                                        </td>                                        <td>                                            @item.quantidade                                        </td>                                        <td>                                            <button onclick="return false;">Excluir</button>                                        </td>                                    </tr>                                }                            </tbody>                        </table>
  14. Can anyone help?

    I have 2 DropDownList, when I select item 1 of the first segudo the loads as the corresponding sub-items. The problem is when I save, because the Drop second id appears as undefined.

    If I set a value for "id", "options += '<option value="1">' + val["descricao"] + '</option>';" the code works:
    What's wrong with "val"? ' + val["id"] + '

     

      $("#cod_Prod_Med_Formula").change(function () {        var dados = $(this).val().toString();            var PrincipioID = $("#Formula_Existente").val();        var options = '';        if (dados != 0) {            $.ajax({                url: '@Url.Action("RetornaFormula", "Medicamento_Produto")',                type: 'POST',                dataType: 'json',                data: { codigo: dados },                success: function (result) {                    $.each(result, function (key, val) {                        if (val["id"] != PrincipioID)                            options += '<option value="' + val["id"] + '">' + val["descricao"] + '</option>';                        else                            options += '<option value="' + val["id"] + '" selected>' + val["descricao"] + '</option>';                    });                    $("#cod_Principio_Ativo").html(options);                }            });        } else {            console.log(options)            $("#cod_Principio_Ativo").html(options);        }    }).change();</script>CONTROLLER: 

    [HttpPost]public ActionResult RetornaFormula(string codigo){var _Codigo = Convert.ToInt32(codigo);var query = from c in db.Prod_Med_Produto_Formulawhere c.id == _Codigoselect new { c.cod_Principio_Ativo, c.Prod_Med_Principio_Ativo.descricao};return Json(query);}

     

    Noting the console appears indefindo value:

    <div class="editor-field col-md-6">
    <select name="cod_Principio_Ativo" class="form-control" id="cod_Principio_Ativo">
    <option value="undefined">Febendazol</option>
    </select>
    </div>
    </div>
  15. Resolved, rsrsr

    <script>       function ToJavaScriptDate(value) {        var pattern = /Date(([^)]+))/;        var results = pattern.exec(value);        return new Date(parseFloat(results[1]));    }</script><!-- Script--><script type="text/javascript">    google.load('visualization', '1.1', { 'packages': ['corechart'] });    google.setOnLoadCallback(drawChart);       function drawChart() {        $.get('/Programa_Nutricao/Avaliacao/EvolucaoPeso', {},              function (data) {                                   var tdata = new google.visualization.DataTable();                           tdata.addColumn('date', 'data_semanal');                  tdata.addColumn('number', 'peso_kg');                                   for (var i = 0; i < data.length; i++) {                                            if (data[i].data_semanal != null)                          tdata.addRow([ToJavaScriptDate(data[i].data_semanal), parseFloat(data[i].peso_kg)]);                                                                                       console.log(ToJavaScriptDate(data[i].data_semanal), data[i].peso_kg);                  }                             var options = {                      width: 700,                      height: 500,                      vAxis: { title: "PESO", minValue: 1, maxValue: 6 },                      hAxis: { title: "DATA", textStyle: { fontSize: 10 }},                      legend: { position: "none" }                                       };                                var chart = new google.visualization.LineChart(document.getElementById('EvolucaoPeso'));                  chart.draw(tdata, options);              });          }</script>
  16. The chart is not out yet. The code return format below:

    <script>       function ToJavaScriptDate(value) {        var pattern = /Date(([^)]+))/;        var results = pattern.exec(value);        return new Date(parseFloat(results[1]));    }</script>

    Tue Sep 02 2014 00:00:00 GMT-0300 (Hora oficial do Brasil) "1.340 "

    Sat Sep 06 2014 00:00:00 GMT-0300 (Hora oficial do Brasil) "1.450 "

    Mon Sep 08 2014 00:00:00 GMT-0300 (Hora oficial do Brasil) "1.540 "

×
×
  • Create New...