Help with a Dropdownlist

Asked

Viewed 55 times

1

I’m having trouble recording the value of my dropdownlist in the bank. When I do Debugger I realize that I am saving the ID values and not the selected items. How can I fix this.

This is my View:

<!--VEICULO-->
<div class="tab-pane" id="VEICULO">
  <div class="row">
    <h4 class="info-text"> Let's start with the basic information (with validation)</h4>

    <div class="col-sm-8 col-sm-offset-2">
      <div class="form-group">
        <label>Marca do veículo</label> @if (ViewBag.MarcaList != null) { @Html.DropDownListFor(Model => Model.MarcaId, ViewBag.MarcaList as SelectList, "-- Selecione a marca do veículo --", new { @class = "form-control" }) }

      </div>
      <div class="form-group">
        <label>Modelo do veículo</label> @Html.DropDownListFor(m => m.ModeloId, new SelectList(""), "-- Selecione o modelo --", new { @class = "form-control" })
      </div>
      <div class="form-group">
        <label>Versão do veículo</label> @Html.DropDownListFor(m => m.VersaoId, new SelectList(""), "-- Selecione a versão --", new { @class = "form-control" })

      </div>
    </div>


  </div>
</div>

My controller:

 public class ClienteController : Controller
{
    private DBContext db = new DBContext();

    // GET: Cliente
    public ActionResult Index()
    {
        return View(db.Clientes.ToList());
    }
    //GET: Enviado
    public ActionResult Enviado()
    {
        return View();
    }

    // GET: Cliente/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Cliente cliente = db.Clientes.Find(id);
        if (cliente == null)
        {
            return HttpNotFound();
        }
        return View(cliente);
    }

    // GET: Cliente/Create
    public ActionResult Create()
    {
        DBContext sd = new DBContext();
        ViewBag.MarcaList = new SelectList(GetMarcalist(), "MarcaId", "Marca");
        return View();

    }
    public List<MarcaVeiculo> GetMarcalist()
    {
        DBContext sd = new DBContext();
        List<MarcaVeiculo> marcas = sd.marcaVeiculos.ToList();
        return marcas;
    }
    public ActionResult GetmodeloList(int MarcaId)
    {
        DBContext sd = new DBContext();
        List<ModeloVeiculo> selecteList = sd.modeloVeiculos.Where(x => x.MarcaId == MarcaId).ToList();
        ViewBag.modeloList = new SelectList(selecteList, "ModeloId", "Modelo");
        return PartialView("Displaymodelos");
    }


    // POST: Cliente/Create
    // Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para 
    // obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Cliente cliente)
    {
      if (ModelState.IsValid)
     {
        db.Clientes.Add(cliente);
        db.SaveChanges();

     }
        return Json(new { Resultado = cliente.Id }, JsonRequestBehavior.AllowGet);

        // return View(cliente);
    }

        // GET: Cliente/Edit/5
        public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Cliente cliente = db.Clientes.Find(id);
        if (cliente == null)
        {
            return HttpNotFound();
        }
        return View(cliente);
    }

    // POST: Cliente/Edit/5
    // Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para 
    // obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Nome,Email,Telefone")] Cliente cliente)
    {
        if (ModelState.IsValid)
        {
            db.Entry(cliente).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(cliente);
    }

    // GET: Cliente/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Cliente cliente = db.Clientes.Find(id);
        if (cliente == null)
        {
            return HttpNotFound();
        }
        return View(cliente);
    }

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

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

And the jquery I’m using to write the data to DB:

function SalvarCliente() {
debugger;

var nome = $("#Nome").val();
var email = $("#Email").val();
var telefone = $("#Telefone").val();

var marca = $("#MarcaId").val();

var modelo = $("#ModeloId").val();
var versao = $("#VersaoId").val();

var residencia = $("#Residencia").val();
var PossuiSeguro = $("#PossuiSeguro").val();

var token = $('input[name="__RequestVerificationToken"]').val();
var tokenadr = $('form[action="/Cliente/Create"] input[name="__RequestVerification"]').val();

var headers = {};
var headersadr = {};
headers['__RequestVerificationToken'] = token;
headersadr['__RequestVerificationToken'] = tokenadr;

var url = "/Cliente/Create";
$.ajax({
    url: url
    , type: "POST"
    , datatype: "json"
    , headers: headersadr
    , data: { Id: 0, Nome: nome, Email: email, Telefone: telefone, MarcaId: marca, ModeloId: modelo, VersaoId: versao, Residencia: residencia, PossuiSeguro: PossuiSeguro, __RequestVerificationToken: token }
    , success: function (data) {
        if (data.Resultado > 0) {



        }
    }
});

}

  • Understood! I’m new to forum and programming. So there must be a lot of errors in the source. I started as a hobby for 2 weeks. I have this project that simulates an insurance quote. Like Bidu and Minute. I was having problems with 3 dropdownlists in Cascading, which returns me the brand of the vehicle, then its model and the latest version. I’m recording the data into the database by a Jquery. But the problem was that these dropdownlists returned their respective id (Marcaid, Modeloid and Versaoid) and not the selected value. I changed then in Jquery, for example var Marcaid = $("#Marcaid"). val(); Coloq

  • I forgot to mention the tables are built through the Entityframework (code first).

  • I don’t get it, you want to write the brand name on the bank and not her id, which would actually be your reference key?

1 answer

-1

I managed to sort it out like this:

I changed the .val(), for (option:selected).text();

  • 2

    It’s okay that the code is yours and Talz, but you could be more specific... Which .val() have you changed? Always remember that in the future someone may have the same question and your answer may be useful! ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.