Pass parameter to a C # MVC Controller

3

I'm learning ASP.NET MVC C # programs and would like to know how I pass data from a textbox to a controller. That is, I want to enter a value (id) in the View Index in a textbox and when I click Submit it returns me to View Details with the id that I typed in the Index view. This example is it pick up by the Name, Tel and CPF through the id that I type in the view index. The view details is working perfectly, when I pass the id by url it shows me the data of the person.

Controller

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    public ViewResult Details(int id )
    {
        ClienteEntity cliente = new ClienteEntity(id);
      //  var cli = cliente.FetchUsingPK(id);
        return View(cliente);
    }

}



    {
        ClienteEntity cliente = new ClienteEntity(id);
      //  var cli = cliente.FetchUsingPK(id);
        return View(cliente);
    }

}

View of the Index

@{
ViewBag.Title = "Index";
}
<h2>Digite um Numero: @Html.TextBox("id")</h2>
<input type="submit" value="Enviar" />

View the Details

<h2>Dados Do Cliente</h2>
<h2>Nome: @Model.NomeCliente</h2>
<h2>CPF: @Model.Cpf</h2>
<h2>Tel: @Model.Tel</h2>
    
asked by anonymous 11.08.2015 / 18:40

1 answer

7

Some things were missing:

In your View Index :

@{
    ViewBag.Title = "Index";
}

@using (Html.BeginForm()) 
{
    <h2>Digite um Numero: @Html.TextBox("id")</h2>
    <input type="submit" value="Enviar" />
}

This is because you will send information to a Controller , so it does not make sense to have a TextBox without a form containing it.

In Controller , add a method that accepts the POST of the submitted information, as below:

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(int id)
    {
        return RedirectToAction("Details", new { id = id });
    }

    public ViewResult Details(int id)
    {
        ClienteEntity cliente = new ClienteEntity(id);
      //  var cli = cliente.FetchUsingPK(id);
        return View(cliente);
    }

}


    /* Comentei esta parte porque ela não faz sentido no seu código.
    {
        ClienteEntity cliente = new ClienteEntity(id);
      //  var cli = cliente.FetchUsingPK(id);
        return View(cliente);
    } */

}
    
11.08.2015 / 18:53