MVC asp.Net problem that i can't solve

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.

This is the way i made for tables, if you understand something just let me know


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

You are going to have to retrieve and populate the Cities and States dropdowns by using a function in your controller. Then you populate a model with the data and use it to build your select. This is how I do it in one of our apps:

First, we have a function to get all the states and pass it in the ViewBag:

CountryRegion[] HomeStates = GetCountryRegionsListByCC(HomeCountry); // queries Country Regions table by Country Code
ViewBag.HomeStates = HomeStates;

Here’s our Model:

public class CountryRegion {
    public int RegionId { get; set; }
    public string CountryCode { get; set; }
    public string StateCode { get; set; }
    public string StateName { get; set; }
}

Then, in the view, iterate through the ViewBag.HomeStates object to fill the select:

<select id="HomeState" name="HomeState">
    <option value="">NONE</option>
@foreach (CountryRegion s in ViewBag.HomeStates)
{
    string sel = (ViewBag.part.HomeState == s.StateCode ? "selected=\"selected\"" : "");
    <option value="@s.StateCode" @Html.Raw(sel)>@s.StateName</option>
}
</select>

We also have some Javascript that will update the State when they select a country:

$("#HomeCountry").change(function () {
    $("#HomeState").load("/Home/GetStates?Country=" + $(this).val() + "&Type=H");
})

Calling this Controller function:

public string GetStates(string Country, string Type, string State) 
{
    string HTMLResult;
    CountryRegion[] States = GetCountryRegionsListByCC(Country);
    HTMLResult = "<option value=\"\">Please select a State, Region or Province</option>";
    HTMLResult += "<option value=\"\">NONE</option>";
    foreach (CountryRegion c in States)
    {
        string sname = "";
        switch (Type)
        {
            case "B":
                sname = BusinessState;
                break;
            case "H":
                sname = HomeState;
                break;
        }

        string sel = (sname == c.StateCode ? "selected=\"selected\"" : "");
        HTMLResult += "<option value=\""+c.StateCode+"\"" + sel + ">"+c.StateName+"</option>";
    }

    return HTMLResult;
}

We do the same thing for Countries and you could do the same for Cities, as well.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.