refer to the logged in user’s id if missing

Asked

Viewed 40 times

1

I’m doing a Net Core MVC point card project, in which I have user, company and employee registration. To register the company I need to get the id of the logged in user, I already have a function that does this and it works for use to register addresses.

// GET: Empresas/Create
    public async Task<IActionResult> Create()
    {
        _logger.LogInformation("Nova empresa");
        var usuario = await _usuarioRepositorio.PegarUsuarioLogado(User);
        var empresa = new Empresa {UsuarioId = usuario.Id}; //aqui tem a referencia do ID certinho
        return View();
    }

    // POST: Empresas/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("EmpresaId,CNPJ,RazaoSocial,NomeFantasia,RamoAtividade,InscEstadual,InscMunicipal,Telefone,Email,Rua,Numero,Bairro,Cidade,Estado,UsuarioId")] Empresa empresa)
    {
        if (ModelState.IsValid)
        {
            await _empresaRepositorio.Inserir(empresa);//mas quando passa pra cá ela se perde e fica como "NULL"

            _logger.LogInformation("Novo empresa cadastrado");
            return RedirectToAction("Index", "Usuarios");
            //return RedirectToAction(nameof(Index));
        }
        _logger.LogError("Informações inválidas");
        return View(empresa);
    }

in the company statement has the user, but when it goes through the view and will insert lose the reference (consigui confirm this through the Debugger), what will be the reason of having lost?

in views->Company->Create I have the visualization of all fields, and the user is hidden

<input asp-for="UsuarioId" type="hidden" />
  • 1

    In the method Create() you are not passing the company object, try return View(empresa)

  • @That’s what Vanderleipires was, thank you!

1 answer

1

You are not returning the company to the View.

Try to do so:

// GET: Empresas/Create
    public async Task<IActionResult> Create()
    {
        _logger.LogInformation("Nova empresa");
        var usuario = await _usuarioRepositorio.PegarUsuarioLogado(User);
        var empresa = new Empresa {UsuarioId = usuario.Id};
        return View(**empresa**);
    }

After this, make sure your view is returning the company object to the controller in POST.

Browser other questions tagged

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