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

Asked

Viewed 1,470 times

3

I have to take a value from a variable within a method in the controller on . net, the method is in homeController and returns a json, up to there everything well the code is running and returning the json perfectly but I have to take a value of a variable already and show in html, I know how to send an html input to the method but not the other way, as I do by ajax to take the value defined in the method for example a string.

1 answer

3


First of all, I advise that the only script inline in the file .cshtml is the declaration of variables from Controller, as the way the caminho virtual, Nome do Usuario, etc..

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

Now based on the following Model and Controller.:

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 script (an archive *.js separate. ) to its 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));               
});

Browser other questions tagged

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