0

I'm trying to finish a work for a course and i have a problem for the last few days, with 2 model view controller.
n°1: I have 3 tables one of them its 'Apartments' that has a FK with 'Cities.Id' and 'Cities' has a FK with 'States.Id', I want to people insert new apartments from a form and want them to select the state from a select box, and after that there appear the cities from that state, now the question is how it would be the MVC for that because I don't really understand how to make apartments got a number if you just select a name from other table.

I have This as table format Inmuebles = Apartments, Barrios = Cities, Localidades = States

http://i.stack.imgur.com/zX63i.png

This is the way i made for tables, if you understand something just let me know
http://i.stack.imgur.com/YuXq5.png

after that in MVC i just have an 'add new apartment' page that is a form

@{
ViewBag.Title = "Create";
}

<h2>Publica tu Inmueble</h2>

<form action="@Url.Action("Create", "Inmuebles")" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="titulo">Titulo</label>
        <input id="titulo" name="titulo" type="text" placeholder="Titulo" />
    </div>
    <div class="form-group">
        <label for="titulo">Localidad</label>
        <input id="localidad" name="localidad" type="text" placeholder="Localidad del Inmueble" />
    </div>
    <div class="form-group">
        <label for="descripcion">Descripcion</label>
        <textarea id="descripcion" name="descripcion" placeholder="Ingresa aqui la descripcion"></textarea>
    </div>
    <div class="form-group">
        <label for="descripcion">Precio</label>
        <input type="number" id="precio" name="precio" />
    </div>
    <div class="form-group">
        <label for="descripcion">Ambientes</label>
        <input type="number" id="ambientes" name="ambientes" />
    </div>
    <div class="form-group">
        <label for="tags">Tags</label>
        <input id="tags" name="tags" type="text" placeholder="Tags para una busqueda mas rapida" />
    </div>
    <div class="form-group">
        <label for="imagen">Imagen</label>
        <input id="imagen" name="imagen" type="file" />
    </div>
    <input type="submit" value="Guardar" />
</form>

i have that in my html and i have this in my controller

[HttpPost]
        public ActionResult Create(FormCollection formulario)
        {
            string titulo = formulario["titulo"];
            string descripcion = formulario["descripcion"];
            string localidad = formulario["localidad"];
            string tags = formulario["tags"];

            Inmueble inmueble = new Inmueble();
            inmueble.Titulo = titulo;
            inmueble.Localidad = localidad;
            inmueble.Descripcion = descripcion;
            inmueble.Tags = tags;

            InmueblesManager managerInmuebles = new InmueblesManager();
            int idInsertado = managerInmuebles.Insertar(inmueble);

            if (Request.Files.Count > 0 &&
                Request.Files[0].ContentLength > 0) //para validar que vino el archivo
            {
                string rutaFinal = Server.MapPath("~/Content/images/inmuebles/" + idInsertado + ".jpg");
                Request.Files[0].SaveAs(rutaFinal);
            }

            return RedirectToAction("Index", "Home");
        }

n°2: Can't delete from database
This is my Controller

public ActionResult Delete(int ID)
        {
            InmueblesManager manager = new InmueblesManager();
            Inmueble inmueble = manager.Consultar(ID);

            ViewBag.receta = inmueble;
            return View();
        }

        public ActionResult ConfirmDelete(int ID)
        {
            InmueblesManager manager = new InmueblesManager();

            manager.Eliminar(ID);

            return RedirectToAction("Index", "Home");
        }

        public ActionResult Create()
        {
            return View();
        }

and this is the model

public void Eliminar(int id)
        {
            SqlConnection conexion = new SqlConnection("Data Source=USUARIO-PC\\SQLEXPRESS;Integrated Security=True;Initial Catalog=jaera;");

            conexion.Open();

            SqlCommand comando = conexion.CreateCommand();
            comando.CommandText = "Delete from Inmuebles WHERE Id = @Id";
            comando.Parameters.AddWithValue("@Id", id);

            comando.ExecuteNonQuery();

            conexion.Close();
        }
        {
        Inmueble inmueble = new Inmueble();

        SqlConnection conexion = new SqlConnection("Data Source=USUARIO-PC\\SQLEXPRESS;Integrated Security=True;Initial Catalog=jaera;");

        SqlCommand comando = new SqlCommand("SELECT * FROM Inmuebles WHERE Id = @Id");
        comando.Parameters.AddWithValue("@Id", id);
        comando.Connection = conexion;

        DataTable tablaResultado = new DataTable();
        SqlDataAdapter adaptador = new SqlDataAdapter(comando);
        adaptador.Fill(tablaResultado);

        if (tablaResultado.Rows.Count > 0)
        {
            inmueble.Id = (int)tablaResultado.Rows[0]["Id"];
            inmueble.Titulo = tablaResultado.Rows[0]["Titulo"].ToString();
            inmueble.Descripcion = tablaResultado.Rows[0]["Descripcion"].ToString();
            inmueble.Ambientes = (int)tablaResultado.Rows[0]["Ambientes"];
            inmueble.Localidad = tablaResultado.Rows[0]["Localidad"].ToString();
            inmueble.Precio = (int)tablaResultado.Rows[0]["Precio"];
            inmueble.Tags = tablaResultado.Rows[0]["Tags"].ToString();
        }
        else
        {
            inmueble = null;
        }

        conexion.Close();

        return inmueble;
    }

And this is the view

@{
    ViewBag.Title = "Delete";
}

<p>Estás seguro que querés eliminar esta publicación?</p>

<h1>@ViewBag.inmueble.Titulo</h1>
<p>@ViewBag.inmueble.Localidad</p>
<p>@ViewBag.inmueble.Descripcion</p>
<p>@ViewBag.inmueble.Ambientes</p>
<p>@ViewBag.inmueble.Precio</p>
<p>@ViewBag.inmueble.Tags</p>

<p>@Html.ActionLink("Sí", "ConfirmDelete", new { ID = @ViewBag.inmueble.Id })</p>
<p>@Html.ActionLink("No", "Details", new { ID = @ViewBag.inmueble.Id })</p>

And last problem n°3
Can't insert new objects to the database

this is the model

 public int Insertar(Inmueble inmueble)
        {
            SqlConnection conexion = new SqlConnection("Data Source=USUARIO-PC\\SQLEXPRESS;Integrated Security=True;Initial Catalog=jaera;");

            conexion.Open();

            SqlCommand comando = conexion.CreateCommand();
            comando.CommandText = "insert into Inmuebles (Titulo, Descripcion, Ambientes, Precio, Localidad, Tags, Usuario)" +
                "output inserted.Id values ('" + inmueble.Titulo + "', '" + inmueble.Descripcion + "', '" + inmueble.Ambientes + "', '" + inmueble.Precio + "', '" + inmueble.Localidad + "', '" +
                inmueble.Tags + "', ' )";

            int nuevoId = (int)comando.ExecuteScalar();
            inmueble.Id = nuevoId;

            conexion.Close();

            return nuevoId;
        }

this is the controller

public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(FormCollection formulario)
        {
            string titulo = formulario["titulo"];
            string descripcion = formulario["descripcion"];
            int precio = Convert.ToInt32(formulario["precio"]);
            int ambientes = Convert.ToInt32(formulario["ambientes"]);
            string localidad = formulario["localidad"];
            string tags = formulario["tags"];

            Inmueble inmueble = new Inmueble();
            inmueble.Titulo = titulo;
            inmueble.Localidad = localidad;
            inmueble.Precio = precio;
            inmueble.Ambientes = ambientes;
            inmueble.Descripcion = descripcion;
            inmueble.Tags = tags;

            InmueblesManager managerInmuebles = new InmueblesManager();
            int idInsertado = managerInmuebles.Insertar(inmueble);

            if (Request.Files.Count > 0 &&
                Request.Files[0].ContentLength > 0) //para validar que vino el archivo
            {
                string rutaFinal = Server.MapPath("~/Content/images/inmuebles/" + idInsertado + ".jpg");
                Request.Files[0].SaveAs(rutaFinal);
            }

            return RedirectToAction("Index", "Home");
        }

i know its a big article and sorry for all, i'm new in asp.net and model view controlller but i'm trying to learn as fast as i can

2
Contributors
1
Reply
9
Views
1 Year
Discussion Span
Last Post by pritaeas
0

When you say "can't insert/delete", are you getting exceptions? What is (or isn't) happening exactly?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.