0

Estoy tratando de guardar un archivo en un base de datos de SQL SERVER 2008 y no estoy consiguiendo mandar los datos al lado del servidor o no estoy recibiendolos bien no lo sé.

introducir la descripción de la imagen aquí Aquí esta mi código:

Front-End

@model  PCotiza_compras.Models.testsoru

@{
ViewBag.Title = "Kyo_2";
}
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>

<div class="container">
<div class=row"">
    <div class="col-xs-12">
        <script>
            var f = new Date();
            document.write(f.getDate() + "/" + (f.getMonth() +1) + "/" + f.getFullYear());
        </script>
    </div>
    <div class="col-lg-6">

      @using (Html.BeginForm("KyoTest", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { 
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Firstname</th>
                        <th>Lastname</th>

                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Nombre</td>
                        <td>
                            <input type="text" placeholder="NombreDeProyecto" id="name" />
                        </td>

                    </tr>
                    <tr>
                        <td>Formato</td>
                        <td>
                            <label>Formato: </label><input type="file" id="format" name="files[]" multiple />
                            <output id="list"></output>

                            <script>
                                              function handleFileSelect(evt) {
                                                var files = evt.target.files; // FileList object

                                                // files is a FileList of File objects. List some properties.
                                                var output = [];
                                                for (var i = 0, f; f = files[i]; i++) {
                                                    output.push('<h4>Datos de archivo</h4>', '<label>Nombre: </label><li>', escape(f.name),
                                                                '<input class="hidden" type="text" id="fn"  name="name" value="', escape(f.name), '" /></li>',
                                                                '<label>Tipo: </label><li>', f.type || 'n/a',
                                                               '<input class="hidden" type="text"  id="ft"  name="name" value="', f.type, '" /></li>',
                                                               '<label>Bytes: </label><li> ', f.size,
                                                                '<input class="hidden" type="text"  id="fs"  name="name" value="', f.size, '" /></li>',
                                                               ' <label>Modificado: </label><li> ',
                                                              f.lastModifiedDate.toLocaleDateString(), '</li>');
                                                }
                                                document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
                                              }

                                              document.getElementById('format').addEventListener('change', handleFileSelect, false);
                            </script>
                        </td>

                    </tr>
                    <tr> 
                        <td>Wiw</td>
                        <td>
                            <p>
                                @Session["Wiw"]
                                <input type="text" class="hidden" id="wiw" value="@Session["WiW"]" />
                            </p>
                        </td>

                    </tr>
                    <tr>
                        <td>
                            <input type="button" onclick="trymeplz()" name="name" value="trymeplz" />
                            <input type="submit" value="Upload Image" />
                        </td>
                    </tr>
                </tbody>
            </table>
      }
</div>
    <div class="col-lg-6">
        <output id="list"></output>
    </div>
</div>
</div>
<script>
  function  trymeplz(){
  var obj = {};

  var dt = new Date();
  obj.namePro = $("[id*=name]").val();
  obj.format = $('#format').prop("files")[0];
  obj.wiw = document.getElementById("wiw").value;
  obj.fname = document.getElementById("fn").value;
  obj.sz = document.getElementById("fs").value;
  obj.ftype = document.getElementById("ft").value;
  obj.dt = dt.getDate() + "/" + (dt.getMonth() + 1) + "/" + dt.getFullYear();

   
  var jsonob = JSON.stringify(obj);
  alert(jsonob);
        $.ajax({
                url: '@Url.Action("KyoTest", "Home")',
                method: "POST",
                dataType: 'json',
                data: jsonob,
                processData: false,
                contentType: 'multipart/form-data',
                success: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
                },
                error: function(er){
                    alert("something got wrong" + er);
                }
        });
  }
</script>

Back-End/ Server side

[HttpPost]
public ActionResult KyoTest(testsoru form) {

  string constr = "Data Source=DMX87025;Initial Catalog=DB_PCC;Integrated Security=True";



  using(SqlConnection con = new SqlConnection(constr)) {
    string query = "INSERT INTO Testsoru([Name],[Wiw],[Formato],[Size],[FName],[Type])" +
      " VALUES(@Name,@wiw,@format,@Size,@FName,@Type)";

    using(SqlCommand cmd = new SqlCommand(query)) {
      cmd.Connection = con;
      cmd.Parameters.AddWithValue("@Name", form.name);
      cmd.Parameters.AddWithValue("@wiw", form.wiw);
      cmd.Parameters.AddWithValue("@format", form.formato);
      cmd.Parameters.AddWithValue("@Size", null);
      cmd.Parameters.AddWithValue("@FName", null);
      cmd.Parameters.AddWithValue("@Type", null);
      con.Open();
      cmd.ExecuteNonQuery();
      con.Close();
      con.Close();
    }

  }


  return View(form);
}
//----Modelo de datos

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PCotiza_compras.Models {
  public class testsoru {

    public int id {
      get;
      set;
    }
    public string name {
      get;
      set;
    }
    public string wiw {
      get;
      set;
    }
    public string size {
      get;
      set;
    }
    public string ftype {
      get;
      set;
    }
    public string fname {
      get;
      set;
    }

    public HttpPostedFileWrapper formato {
      get;
      set;
    }
  }
}

4
  • el error que mostras habla de un SP.. y no veo ninguna llamada a un SP en tu codigo..
    – gbianchi
    el 10 nov. 2017 a las 17:59
  • Disculpa @gbianchi pero que es SP? si lo olvidé lo incluyo el 10 nov. 2017 a las 18:01
  • tu error habla de una consulta parametrizada. ese error se produce en alguna de estas lineas de codigo? y aparte de eso, no pongas una imagen de tu error, pon el error que te sale completo.
    – gbianchi
    el 10 nov. 2017 a las 18:03
  • Pues solo me sale esa ventanilla de error, quieres que ponga lo qyue viene en el output?? @gbianchi el 10 nov. 2017 a las 18:38

1 respuesta 1

1

Para referencia, ya que la pregunta modificó el error reportado. Este era el error en la pregunta:

introducir la descripción de la imagen aquí


Este error sucede cuando el valor que le pasas a AddWithValue es null. Aunque yo tampoco entiendo porqué es así, pero para asignar un null, debes usar DBNull.Value en su lugar.

De modo que, para corregir el error, modifica tu código para que se parezca a algo así:

  cmd.Parameters.AddWithValue("@Name", form.name ?? DBNull.Value);
  cmd.Parameters.AddWithValue("@wiw", form.wiw ?? DBNull.Value);
  cmd.Parameters.AddWithValue("@format", form.formato ?? DBNull.Value);
  cmd.Parameters.AddWithValue("@Size", DBNull.Value);
  cmd.Parameters.AddWithValue("@FName", DBNull.Value);
  cmd.Parameters.AddWithValue("@Type", DBNull.Value);

Como no conozco los tipos, estoy asumiendo que tanto form.name, form.wiw como form.formato todos pueden estar a null. Si alguna de estas propiedades nunca puede ser null, no necesitas la expresión ?? DBNull.Value en ese caso.

4
  • Hola , oye no me funcionó esto sigo teniendo el mismo error, me dice que no le estoy pasando nada el 13 nov. 2017 a las 16:48
  • ¿Cual es el error exacto que recibes? Estoy casi seguro que no es el mismo al de la pregunta.
    – sstan
    el 13 nov. 2017 a las 18:19
  • @staan listo ya subí los cambios y el error el 13 nov. 2017 a las 18:44
  • ¿Por qué decías que el error es el mismo, si no se parece en nada? Y ahora con los detalles que has puesto, 1) la respuesta que te di ya no tiene sentido porque quitastes el error original. 2) no hay manera de identificar el origen del error. En realidad, lo que parece es que al aplicar mi sugerencia, esto corrigió tu problema original, y ahora se puede ver que tienes otro error. Esto debería ser una pregunta separada.
    – sstan
    el 13 nov. 2017 a las 18:53

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.