0

I'm using ADO.NET and I want to know how can I change data from the table depending on my dropdownlist value. Here's my view

@model IEnumerable<MVCcrud01.repuesto>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.DropDownList("Modelos", ViewBag.datos as SelectList, "Seleccione un modelo...")

<p>
    @Html.ActionLink("Create New", "Create")    
</p>
<table class="table" id="grid">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.nombre)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.precio)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.descuento)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.modelo.modelo1)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.nombre)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.precio)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.descuento)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.modelo.modelo1)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.id_rep }) |
                @Html.ActionLink("Details", "Details", new { id = item.id_rep }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.id_rep })
            </td>
        </tr>
    }
</table>

And here's my controller:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCcrud01;

namespace MVCcrud01.Controllers
{
    public class repuestoesController : Controller
    {
        private autosEntities db = new autosEntities();

        // GET: repuestoes
        public ActionResult Index()
        {
            var repuestos = db.repuestos.Include(r => r.modelo);
            ViewBag.datos = new SelectList(db.modelos, "id_modelos", "modelo1");

            return View(repuestos.ToList());
        }

        // GET: repuestoes/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            repuesto repuesto = db.repuestos.Find(id);

            if (repuesto == null)
            {
                return HttpNotFound();
            }

            return View(repuesto);
        }

        // GET: repuestoes/Create
        public ActionResult Create()
        {
            ViewBag.id_modelos = new SelectList(db.modelos, "id_modelos", "modelo1");
            return View();
        }

        // POST: repuestoes/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "id_rep,nombre,precio,descuento,id_modelos")] repuesto repuesto)
        {
            if (ModelState.IsValid)
            {
                db.repuestos.Add(repuesto);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.id_modelos = new SelectList(db.modelos, "id_modelos", "modelo1", repuesto.id_modelos);
            return View(repuesto);
        }

        // GET: repuestoes/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            repuesto repuesto = db.repuestos.Find(id);

            if (repuesto == null)
            {
                return HttpNotFound();
            }

            ViewBag.id_modelos = new SelectList(db.modelos, "id_modelos", "modelo1", repuesto.id_modelos);
            return View(repuesto);
        }

        // POST: repuestoes/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "id_rep,nombre,precio,descuento,id_modelos")] repuesto repuesto)
        {
            if (ModelState.IsValid)
            {
                db.Entry(repuesto).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.id_modelos = new SelectList(db.modelos, "id_modelos", "modelo1", repuesto.id_modelos);
            return View(repuesto);
        }

        // GET: repuestoes/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            repuesto repuesto = db.repuestos.Find(id);

            if (repuesto == null)
            {
                return HttpNotFound();
            }

            return View(repuesto);
        }

        // POST: repuestoes/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            repuesto repuesto = db.repuestos.Find(id);
            db.repuestos.Remove(repuesto);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

I have default data charged from the database and I want it to be dynamic depending on the dropdownlist selected value. I'll be grateful with you guys!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

Probably you want to use AJAX callback which returns table rows like this:

$('#Modelos').change(function () {
    var selected = $(this).val(); // get selected value from dropdown

    var targetUrl = '@Url.Action("GetResults", "ControllerName")';
    var param = { id: selected };

    $.ajax({
        url: targetUrl,
        type: 'GET',
        data: param,
        dataType: 'json',
        success: function (response) {
            var row = '';

            // this part depends on JSON structure, here is just an example
            $.each(response, function(i, value) {
                row += '<tr><td>' + [...] + '</td></tr>'; // build table rows with each column values
            }

            // use append() to add new rows, or html() to replace existing rows
            $('#grid tbody').html(row);
        }
    });
});

Note: Adding <tbody> tag is recommended to differentiate content section from table headers, so that content section can be updated dynamically from AJAX response.

Also don't forget to create an action method returning JsonResult which has same name as mentioned in @Url.Action() helper above:

public JsonResult GetResults(int id)
{
    // example query from table
    var list = db.repuestos.Where(x => x.nombre == id).Select(x => new {
        nombre = x.nombre,
        precio = x.precio,
        descuento = x.descuento,
        // other properties here
    }).ToList();

    // return JSON data
    return Json(list, JsonRequestBehavior.AllowGet);
}
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • Should I put the script inside the layout view? – Manuel Alfaro Sep 18 '18 at 15:12
  • You can put the script inside view page, where putting inside (base) layout only if the script are shared across multiple pages. – Tetsuya Yamamoto Sep 18 '18 at 15:25
  • Do you know why I'm getting this error? System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.modelo_CF7F16B4ADA5ECA3363FD4C72D821CF77FD69C43CA39A7152875B9364A1DDB8E'. – Manuel Alfaro Sep 19 '18 at 05:58
  • You need to return only just required properties. The error indicates circular reference in your entity properties hierarchy which doesn't supported by JSON serializer, see further details [here](https://stackoverflow.com/questions/1153385/a-circular-reference-was-detected-while-serializing-an-object-of-type-subsonic/23490311). – Tetsuya Yamamoto Sep 19 '18 at 06:03