How to get value from a variable in the controller with ajax (jquery)

3

I have to get a value from a variable inside a method in the controller in .net, the method is in the homeController and returns a json, so alright the code is running and returning the json perfectly but I have to get a value of a variable already and show in html, I know how it does to send an input from html to the method but not the other way, as I do by ajax to get the value defined in the method eg a string.

    
asked by anonymous 02.08.2016 / 19:40

1 answer

3

First of all, I advise that the only% inline% in the script file is the declaration of variables from .cshtml , such as path Controller , caminho virtual , etc.

<script type="text/javascript">
    var baseURL = "@Url.Content("~/")";
</script>

Now based on the following Nome do Usuario and Model :

Model

namespace AjaxSample
{
    public class TextoModel
    {
        public string Frase { get; set; }
    }
}

Controller

using System;
using System.Web.Mvc;
using System.Web.Http;
using System.Linq;

namespace AjaxSample
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View(new TextoModel() { Frase = "Hello Wolrd" });
        }


        [HttpPost]
        public JsonResult Inverter([FromBody] TextoModel model)
        {               
            model.Frase = String.Join("", model.Frase.Reverse());
            return Json(model);
        }
    }
}

View

<body>
    <div class="container">
        @using (Html.BeginForm())
        {
        <div class="form-group">
            @Html.LabelFor(m => m.Frase)
            @Html.TextBoxFor(model => model.Frase, new {@class="form-control"}) 
            @Html.ValidationMessageFor(model => model.Frase)
        </div>

        <button type="button" class="btn btn-success submit" id="inverter">Inverter</button>
        }
    </div>
</body>

You can add your Controller (a script pendent.% file) to your page.

Script

var inverter = document.getElementById("inverter");
var frase = document.getElementById("Frase");
inverter.addEventListener("click", function (event) {
  var data = { Frase: frase.value };
  var httpRequest = new XMLHttpRequest();
  httpRequest.open("POST", baseURL + "Home/Inverter", true);
  httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  httpRequest.responseType = "json";
  httpRequest.addEventListener("click", function() {
    if (httpRequest.readyStatus == 4) {
      if (httpRequest.status == 200) {
        var data = httpRequest.response; // objeto retornado pela Action Inverter.
        frase.value = data.Frase; // atribuindo o novo valor ao input.
      } else {
        console.log("Ocorreu um erro na requisição");
      }
    }
  });
  httpRequest.send(JSON.stringify(data));               
});
    
02.08.2016 / 20:35