1
I’m trying to insert an object containing a relationship.
User > Enterprise
First I need to get the data from User in View
of Create I’m doing it this way:
public ActionResult Create()
{
var usuarioLogado = User.Identity.Name;
var usuarioDb= new SelectList(db.Users.Where(u => u.Email == usuario), "Id", "Email");
ViewBag.UsuarioId = UsuarioDb;
return View();
}
And my View
who receives:
<div class="form-group formulario">
@Html.LabelFor(model => model.Usuario.Email, htmlAttributes: new { @class = "control-label col-md-2", })
<div class="col-md-10">
@* @Html.EditorFor(model => model.UsuarioId, new { htmlAttributes = new { @class = "form-control", @disabled = "disabled", @Value = ViewBag.UsuarioId } })*@
@Html.DropDownList("UsuarioId", null, htmlAttributes: new { @class = "form-control", @disabled = "disabled" })
@Html.ValidationMessageFor(model => model.UsuarioId, "", new { @class = "text-danger" })
</div>
</div>
However, when sending the data to my controller
Post
:
public async Task<ActionResult> Create([Bind(Include = "EmpresaId,UsuarioId,Nome,Cnpj")] Empresa empresa)
{
if (ModelState.IsValid)
{
empresa.EmpresaId = Guid.NewGuid();
db.Empresa.Add(empresa);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.UsuarioId = new SelectList(db.Users, "Id", "Email", empresa.UsuarioId);
return View(empresa);
}
get the bug:
The INSERT statement conflicted with the FOREIGN KEY Constraint "Fk_dbo.Empresas_dbo.Aspnetusers_usuarioid". The Conflict occurred in database "Patrimoniocontexto", table "dbo.Aspnetusers", column 'Id'. The statement has been terminated.
What is the correct way to enter the data ?
Remove the disabled from
DropDownList()
.– Randrade