Link call method in Controller - C # MVC

0

I have a MySQL table that is displayed on a page of my project:

foreach (var item in Model)
{

   <tr>
       <td>@Html.DisplayFor(modelItem => item.id)</td>
       <td>@Html.DisplayFor(modelItem => item.nomeMarca)</td>
       <td>
          <a>Deletar</a> &ensp;
          <a>Renomear</a> 
       </td>
   </tr>

I want the user to click on the link with the text "Delete" to send the item (from the "Tag" model) to the Controller:

[HttpGet]
    public ActionResult RemoveMarca(Marca m)
    {
        MarcasDAO marca = new MarcasDAO();
        int i = marca.deletaMarca(m);
        if (i > 0)
        {
            ViewBag.Message2 = "Marca removida com sucesso!";
            return AddMarca();
        }
        else
        {
            ViewBag.Message2 = "Erro ao remover a marca";
            return AddMarca();                    
        }
    }

In the "brandname (m)" tag, you have the following code to remove the mark from the table:

public int deletaMarca(Marca m)
    {
        try
        {
            comando.CommandText = "delete from Marca where idMarca = @id";
            comando.Parameters.AddWithValue("@id", m.id);
            comando.Connection = con_sql;
            int i = comando.ExecuteNonQuery();
            comando.Dispose();
            objcon.Desconectar();
            return i;
        }
        catch (Exception)
        {
            throw;
        }
    }

But I have no idea how to make it work. I've tried some things but it always makes mistakes. The methods for adding a Tag are okay and work for the site.

    
asked by anonymous 04.04.2017 / 11:45

1 answer

2

In your view, in each Table row, you can have ...

   <tr>
      <% using Html.BeginForm("action","controller", new { Id = item.id }, FormMethod.Post); { %>
         <td>@Html.DisplayFor(modelItem => item.id)</td>
         <td>@Html.DisplayFor(modelItem => item.nomeMarca)</td>
         <td><input type="submit" value="Remove Marca" /></td>
      <% } %>
  </tr>

The method on the Controller that receives the ID ...

[HttpPost]
public ActionResult RemoveMarca(Id id)
{
   int i = marca.deletaMarca(id);        
   return RedirectToAction("Index");
}

And deleteMail can only receive the ID ...

public int deletaMarca(Id id)
{
    try
    {
        comando.CommandText = "delete from Marca where idMarca = @id";
        comando.Parameters.AddWithValue("@id", m.id);
        comando.Connection = con_sql;
        int i = comando.ExecuteNonQuery();
        comando.Dispose();
        objcon.Desconectar();
        return i;
    }
    catch (Exception)
    {
        throw;
    }
}
    
04.04.2017 / 12:31