Save Campo Automatico

Asked

Viewed 62 times

1

I have the following situation.

In the Bank, I have the tables State, City, with data duly registered and linked.

In View I would like to put only one Dropdown with the list of Cities, but I would like to automatically record the state id in the bank.

namespace CadastroMVC.Models
{
    public class Class1
    {
        public int CidadeId { get; set; }
        public int EstadoId { get; set; }
        public string NomeCidade { get; set; }
    }
}
  • 2

    Record where? There’s this to put in the question.

  • 3

    Bring the state in a field like hidden.

  • I would like to record the state id in the Cities table automatically, without having to select the state once, that the tables are already listed in the bank.

  • To save the state in a city table, you have to select the state so that the registration knows, it is not automatic...!

2 answers

4

You need to select the Estado again while saving:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Criar(Class1 class1)
    {
        if (ModelState.IsValid)
        {
            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var estado = contexto.Cidades
                                     .Include(c => c.Estado)
                                     .FirstOrDefault(c => c.CidadeId == class1.CidadeId);

                // Verificar aqui se o estado existe, para evitar erros de referência nula.

                class1.EstadoId = estado.EstadoId; // Não é muito correto fazer isso, mas se você faz questão de salvar o EstadoId, tudo bem.
                context.Class1.Add(class1);
                await context.SaveChangesAsync();
                scope.Complete();
            }

            return RedirectToAction("Indice");
        }

        // ViewBags aqui
        return View(class1);
    }

2

From what I understand you want to keep the State Id fixed in your application.

Come to think of it, enough in your method Create fill in the EstadoId with the desired value.

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Criar(Cidade cidade)
        {
            if (ModelState.IsValid)
            {
                //setando o estado
                cidade.EstadoId = 1;
                context.Cidades.Add(cidade);
                await context.SaveChangesAsync();

                return RedirectToAction("Indice");
            }

            await ViewBags();
            return View(cidade);
        }

Browser other questions tagged

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