Button in a View with MVC / Web API

0

When we put a button in a View, how do we trigger a click of it? I have this button:

@model IEnumerable<CarregaDados.Models.Cliente>
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<p>
    @Html.ActionLink("Criar Usuário", "AdicionaUsuario")
</p>
<input type="button" id="btn" value="Teste" onclick=""/>

And I have this controller

public class IndexController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Enviar()
        {
            string uri = "http://www.meu_site.com.br/autorizador/api/getliberaitens/value";

            return null;
        }
        public static string HttpPost(string url, string postData)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            byte[] data = Encoding.ASCII.GetBytes(postData);
            request.Method = "POST";
            request.Accept = "text/plain";
            request.ContentType = "text/plain; charset=utf-8";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            return responseString;
        }
    }

How do I, by the button, trigger any method or Action in the controller?

    
asked by anonymous 19.10.2017 / 16:25

1 answer

0

If you need to do a Post, one option is to use the helper Html.BeginForm to create a form, adjust your code including your HTML code in the form (inside the helper Html.BeginForm) and in your controller set the attribute [HttpPost] in> na action, example:

View:

...
<div class="form-group">
        @using (Html.BeginForm("SuaAction", "SeuController", FormMethod.Post))
        {

        <!-- INSIRA O CÓDIGO HTML DO FORMULÁRIO AQUI -->           
        <input type="submit" id="btn" value="Teste"/>

        }
</div>
...

Controller:

public class SeuController : Controller
{
    ...

    [HttpPost]
    public ActionResult SuaAction()
    {
        return View();
    }
}
    
19.10.2017 / 17:12