Getting record id

1

I have a table with several records and a delete link, how do I, when I click on this link, pass the value of the record id I want to delete? Code of my view:

@model IList<Financas.Entidades.Usuario>

@Html.ActionLink("Novo Usuário", "Form")
<table class="table table-hover">
    <thead>
        <tr>
            <th>Id</th>
            <th>Nome</th>
            <th>E-mail</th>
        </tr>
    </thead>
        <tbody>
            @foreach(var usuario in Model)
            {
                <tr>
                    <td>@usuario.Id</td>
                    <td>@usuario.Nome</td>
                    <td>@usuario.Email</td>
                    <td>@Html.ActionLink("Excluir","Excluir","Usuario")</td>
                </tr>
            }
        </tbody>
</table>

Controller:

    public ActionResult Excluir(int? usuario)
    {
            try
            {
                IList<Usuario> dados = usuarioDAO.GetById(usuario);
                return View(dados);

            }
            catch (Exception)
            {

                throw;
            }
        }
    
asked by anonymous 21.06.2016 / 04:05

2 answers

0

Let's first address the bugs in your code.

The error of the question is simple, you are not passing anything as a parameter to Action . Just change to the following:

   <td>@Html.ActionLink("Excluir","Excluir","Usuario", new{usuario = usuario.Id})</td>

In this way you will be passing an ID to the parameter usuario in your Action .

Now let's make some improvements to your code?

The first :

I do not know what's in your usuarioDAO , but apparently you're just listing a list of users by ID . At no time in your code is there an option to delete.

public ActionResult Excluir(int? usuario)
        {
                try
                {
                    IList<Usuario> dados = usuarioDAO.GetById(usuario);
                    return View(dados);

                }
                catch (Exception)
                {

                    throw;
                }
            }

Second:

If you do not have a View delete confirmation, why leave the option to pass an ID null ? If you are going to delete a user, some data must be passed, that is, you can change the parameter from int? usuario to int usuario . That way you are ensuring that you will always have a value.

Third :

I would change your whole logic just because of this:

public ActionResult Excluir(int id)
            Usuario usuario= db.Usuarios.Find(id);

            if(usuario == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);//Um erro aqui, pois o usuário não foi encontrado

            db.Usuarios.Remove(usuario);
            db.SaveChanges();
            return RedirectToAction("Indice");
}
    
21.06.2016 / 14:26
0

Just go like this:

Html.ActionLink("Excluir", "Excluir", "Usuario", new {id = usuario.Id}, null)
    
21.06.2016 / 04:36