Button on a View with MVC/Web API

Asked

Viewed 624 times

2

When we put a button in a View, how do we fire 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 button, trigger any method or Action in the controller?

  • A web application has not been. Therefore, you do not "trigger" events/methods in controllers. You need to make your method meet some HTTP request and make the button send this request.

  • What do you want the button to do? Call a view or send data to the server?

1 answer

1

If you need to make 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 (within the Html.Beginform helper) and in your controller set the attribute [Httppost] in the 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();
    }
}
  • @pnet The answer was helpful?

Browser other questions tagged

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