locked
Dropdonwlist error RRS feed

  • Question

  • User-543310235 posted

    Hi im new on this, i was creating a app MVC 5 VS 2019 a testing program actually, and i got error with saving form, and searching won web and nothing.

    Web config

      <connectionStrings>
        <add name="PacienteDBContext"  connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Paciente;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Paciente.mdf" providerName="System.Data.SqlClient" />
      </connectionStrings>

    model folder -> clDbContext.cs

    using System.Data.Entity;
    
    namespace MVC2JPacientes.Models
    {
        public class ClDbContext : DbContext
        {
            public ClDbContext()
                : base("PacienteDBContext") //base("DefaultConnection") o base("MircorostConnection")
            {
            }
    
            public DbSet<Paciente> Pacientes { get; set; }
            public DbSet<Genero> Generos { get; set; }
        }
    }

    model folder -> genero.cs

    using System.ComponentModel.DataAnnotations;
    
    namespace MVC2JPacientes.Models
    {
        public class Genero
        {
            [Key]
            public int GeneroId { get; set; }
    
            [Required]
            public string Nombre { get; set; }
        }
    }

    model folder -> paciente.cs

    using System.ComponentModel.DataAnnotations;
    
    namespace MVC2JPacientes.Models
    {
    
        public class Paciente
        {
                    
            [Required]
            [Key]
            public Int64 Id { get; set; }
    
            [Display(Name = "Nombre del paciente")]
            [Required(ErrorMessage = "Nombre requerido")]
            public string PacienteNombre { get; set; }
    
            public int? Age { get; set; }
    
            public decimal? Peso { get; set; }
    
            public decimal? Masa { get; set; }
    
            public decimal? Liquido { get; set; }
            
            [Display(Name = "Genero de la persona")]
            [Required(ErrorMessage = "Genero requerido requerido")]
            [Key]
            public Genero Genero_ { get; set; }
    
            [Required]
            [Display(Name = "Fecha de nacimiento")]
            [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
            [DataType(DataType.Date)]
            public DateTime DoB { get; set; }
    
            [Display(Name = "Email Address:")]
            [Required(ErrorMessage = "The email address is required")]
            [RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "E-mail is not valid")]
            public string Email { get; set; }
    
            public int? Estado { get; set; }
    
        }

    controler folder -> PacienteControler.cs

    namespace MVC2JPacientes.Controllers
    {
        [RouteArea("Admin")]
        public class PacientesController : Controller
        {
            private ClDbContext db = new ClDbContext();
    
            public async Task<ActionResult> Index()
            {
                return View(await db.Pacientes.ToListAsync());
            }
            public ActionResult Create()
            {
                //dropdonlist llenar
                using (ClDbContext Tablas = new ClDbContext())
                {
                    SelectList genero = new SelectList(Tablas.Generos.OrderBy(x => x.GeneroId).ToList(), "GeneroId", "Nombre");
                    ViewBag.Generov_ = genero;
                }
                //dropdonlist llenar
                return View();
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> Create([Bind(Include = "Id,PacienteNombre,Age,Peso,Masa,Liquido,Genero_,DoB,Email,Estado")] Paciente paciente)
            {
    
                if (ModelState.IsValid)
                {
                    db.Pacientes.Add(paciente);
                    await db.SaveChangesAsync();
                    return RedirectToAction("Index");
                }
    
                return View(paciente);
            }


    folder -> Views-> Paciente -> Create.cshtml

            <div class="form-group">
                @Html.LabelFor(model => model.Genero_, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.Genero_, new SelectList(ViewBag.Generov_,"Value","Text")  , "Favor de selecionar uno", new { @class = "form-control" })
    
                    @Html.ValidationMessageFor(model => model.Genero_, "", new { @class = "text-danger" })
                </div>
            </div>

    but when i save get this error

    https://1drv.ms/u/s!AkGgScb34Z8ky06avNBkW_F8y8vg

    https://1drv.ms/u/s!AkGgScb34Z8ky083P2qs8ymbNJLh

    Thanks in advance!

    greetings,

    Juan Solares

    Tuesday, May 19, 2020 5:22 PM

Answers

  • User-474980206 posted

    you don't have the model correct.

    as I stated you need to add the column (which will be used to link to the Genero table);

         public int GeneroId {get; set;}

    to the class Paciente then bind to this new field.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 19, 2020 11:38 PM

All replies

  • User-474980206 posted

    the dropdown posts its value (GeneroId in your case), but you are try to bind this value to an object. you should add a GeneroId (reference key) to the view model.

           @Html.DropDownListFor(model => model.GeneroId, 
                 (SelectList) ViewBag.Generov_,
                 "Favor de selecionar uno",
                 new { @class = "form-control" }).
    

    Tuesday, May 19, 2020 8:26 PM
  • User-543310235 posted

    Hi,

    I tried that, and got an error.

    the sugestion:

    <div class="col-md-10">
      @Html.DropDownListFor(model =>model.Genero_.GeneroId , (SelectList) ViewBag.Generov_  , "Favor de selecionar uno", new { @class = "form-control" })
      @Html.ValidationMessageFor(model => model.Genero_, "", new { @class = "text-danger" })
    </div>

    an the error.

    https://1drv.ms/u/s!AkGgScb34Z8ky1B_FsDwRzAvGiWR

    thanks in advance.

    greetings,

    Juan Solares

    Tuesday, May 19, 2020 8:43 PM
  • User-474980206 posted

    you don't have the model correct.

    as I stated you need to add the column (which will be used to link to the Genero table);

         public int GeneroId {get; set;}

    to the class Paciente then bind to this new field.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 19, 2020 11:38 PM
  • User1686398519 posted

    Hi,  jpsolares

    You need to set ViewBag.Generov_ in the Create Post method. Your page does not need to be modified.

            private Model1 context = new Model1();
            public SelectList Getgenero()
            {
                SelectList genero = new SelectList(context.Generos.OrderBy(x => x.GeneroId).ToList(), "GeneroId", "Nombre");  
                return genero;
            }
            public async Task<ActionResult> Index()
                {
                    return View(await context.Pacientes.ToListAsync());
                }
                public ActionResult Create()
                {
                Paciente paciente = new Paciente();
                //ViewBag.Generov_ = genero;
                ViewBag.Generov_ = Getgenero();
    
                //dropdonlist llenar
                return View(paciente);
                }
    
                [HttpPost]
                [ValidateAntiForgeryToken]
                public async Task<ActionResult> Create([Bind(Include = "Id,PacienteNombre,Age,Peso,Masa,Liquido,Genero_,DoB,Email,Estado")] Paciente paciente)
                {
                string DropDownListValue = Request.Form["Genero_"].ToString();
                paciente.Genero_ = new Genero();
                paciente.Genero_.GeneroId = Int32.Parse(DropDownListValue);
                if (ModelState.IsValid)
                    {
                    context.Pacientes.Add(paciente);
                        await context.SaveChangesAsync();
                        return RedirectToAction("Index");
                    }
                ViewBag.Generov_ = Getgenero();
                return View(paciente);
                }

    Here is the result.

     
    Best Regards,

    YihuiSun

    Thursday, May 21, 2020 9:46 AM
  • User-543310235 posted

    Thanks, and is almost, in the model the name is requiered. Generoid and Nombre is required.

    thanks in advance.

    Juan Solares

    Sunday, May 24, 2020 8:53 PM
  • User-543310235 posted

    Another way is to use the entity framawork doit for u.

    public class Paciente2
        {
    
            [Key]
            public Int64 Id { get; set; }
    
            [Display(Name = "Nombre del paciente")]
            [Required(ErrorMessage = "Nombre requerido")]
            public string PacienteNombre { get; set; }
    
            public int Age { get; set; }
    
            public decimal Peso { get; set; }
    
            public decimal Masa { get; set; }
    
            public decimal Liquido { get; set; }
                    
            [Required]
            [Display(Name = "Fecha de nacimiento")]
            [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
            [DataType(DataType.Date)]
            public DateTime DoB { get; set; }
    
            [Display(Name = "Email Address:")]
            [Required(ErrorMessage = "The email address is required")]
            [DataType(DataType.EmailAddress)]
            [RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "E-mail is not valid")]
            public string Email { get; set; }
    
            [Display(Name = "Estado")]
            [Required(ErrorMessage = "Estado requerido")]
            public int Estadoid { get; set; }
    
            //[NotMapped]
            [Display(Name = "Estado")]
            public virtual Estados2 estados { get; set; }
    
        }
    
        public class Estados2
        {
            [Key]
            public int EstadoId { get; set; }
    
            [Required]
            public string Nombre { get; set; }
    
            public IList<Paciente2> Pacientes_ { get; set; }
        }

    Create the controler to doit all, list, create, edit, view and delelte, with this models, and Entity framework doit for u even the drop down list with related data, is hard work to get here, a lot of days searching, at this point i realize what Microsoft says is true u code less :), but only and only if u have the right model, that dosent show u in the microsoft tutorials, and should.

    Thanks every one, and my two cents.

    Greetings,

    Juan Solares

    Tuesday, May 26, 2020 4:36 AM