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