Error saving record without choosing category in dropdownlist

0

I'm having a problem clicking on save with some data filled up, giving me error how could I solve it.

ClickingsavefromthiserrorThisisthecontrollertocreate        

publicActionResultCreate(Empresaempresa){if(ModelState.IsValid){
db.Empresas.Add(empresa);db.SaveChanges();
returnRedirectToAction("Index");

        }

        ViewBag.CidadeId = new SelectList(CombosHelper.PegarCidade(empresa.DepartamentoId), "CidadeId", "Nome", empresa.CidadeId);
        ViewBag.DepartamentoId = new SelectList(CombosHelper.PegarDepartamento(), "DepartamentoId", "Nome", empresa.DepartamentoId);
        return View(empresa);
    }

This is the function that takes the city.

Home public static List GetCity (int departmentid)         {             var city = db.Cities.Where (cid => cid.DepartamentoId == departmentid) .ToList ();             city.Add (new city             {                 DepartmentId = 0,                 Name="[Select a City]"             }); return cidade = cidade.OrderBy(dep => dep.Nome).ToList(); }

If you choose the department and city, it saves normal, so when you try to save without choosing, you would have to put some message that can not, but I can not.

    
asked by anonymous 09.09.2017 / 02:03

1 answer

0

This is due to the fact that you are assigning the "0" value that does not exist in the related table to the "placeholder".

Remove this snippet and instead of creating the placeholder that way

cidade.Add(new Cidade
            {
                DepartamentoId = 0,
                Nome = "[ Selecione uma Cidade ]"
            });

Insert HTML when creating dropdownlist

@Html.DropDownListFor(m => m.<campo>, Model.<campo>, "[ Selecione uma cidade ]")
    
17.11.2017 / 17:43