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));
});