Pass parameters via post to Controller

Asked

Viewed 5,007 times

1

I have a CSHTML where the fields will turn into parameters, which will be passed via post to an existing method in a controller. How do I do this? I am searching, but I still have doubts about how to pass, as the method will understand that comes from a cshtml.

  • you have everything inside a form?

  • 1

    Post the relevant snippets of your code.

1 answer

1


One of the ways to send parameter via post to your controller is encapsulating your parameters within a form in the CSHTML of the kind POST and sending them through Submit.

You can use the helpers of MVC for this.

Example

In his Model:

 public class PessoaModel
{

    public string Nome {get;set;} 
    public string Senha {get;set;}
}

In your CSHTML View

@model PessoaModel

 @using (Html.BeginForm("Salvar","PessoaController", FormMethod.POST))
 {
    @Html.Label("Nome"):
    @Html.TextBoxFor(e => e.Nome) <br />
    @Html.Label("Senha"):
    @Html.TextBoxFor(e => e.Senha)
 }

In your Controller

public class PessoaController : Controller
{
    [HttpPost]
    public ActionResult Salvar (PessoaModel model)
    {
        //Seu codigo quando a requisição post acontecer
    }    
}

You can also send information POST using a form without the use of a model, using the helpers without the termination is, and having in its controller parameter of the same name passed in the helper.

For example:

In your CSHTML:

@using (Html.BeginForm("Salvar","PessoaController", FormMethod.POST))
 {
    @Html.Label("Nome"):
    @Html.TextBox("Nome") <br />
    @Html.Label("Senha"):
    @Html.TextBox("Senha")
 }

In your Controller

public class PessoaController : Controller
{
    [HttpPost]
    public ActionResult Salvar(string nome, string senha)
    {
        //Seu codigo quando a requisição post acontecer
    }    
}
  • A doubt. I have my cshtml Index(Home), but the parameters come from Home and will be executed in the Step controller and not in the Homecontroller. That’s not a problem?

  • All mvc controllers need to end with the name Controller. For example, Passocontroller (as I understand it). And yes, you can change the controller and action within @Html.Beginform by changing the first two parameters, but depending on the context and your implementation this can get messy.

Browser other questions tagged

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