I'm trying to call a C# function Update()
from the cshtml
.
It should be called whenever the input is changed.
This is Run.cshtml
:
@page
@model RunModel
@{
ViewData["Title"] = "Run";
}
<h1>@ViewData["Title"]</h1>
<p>
<br />
Solve @ViewData["Problem"]
<br />
<input type="text" name="YourInput" autocomplete="off" autofocus onchange="Update()">
<br />
Your input: @ViewData["YourInput"]
</p>
This is Run.cshtml.cs
:
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace Mastery.Pages
{
public class RunModel : PageModel
{
private readonly ILogger<RunModel> _logger;
public RunModel(ILogger<RunModel> logger)
{
_logger = logger;
}
public void OnGet()
{
var node = Run.ChooseNode();
var problem = node.GenerateProblem();
ViewData["Problem"] = problem.Text;
}
public void Update()
{
ViewData["YourInput"] = Request.Query["YourInput"];
}
}
}
How can you call the Update()
function when the cshtml input is changed?
CodePudding user response:
You can use ajax to pass data to handler,and handler return data to ajax,then replace html with the data.Here is a working demo:
<p>
<br />
Solve @ViewData["Problem"]
<br />
<input type="text" name="YourInput" autocomplete="off" autofocus onchange="Update(this)">
<div id="div1">Your input: @ViewData["YourInput"]</div>
</p>
@section scripts
{
<script>
function Update(t) {
var url = '?handler=Update&&YourInput=' $(t).val();
$.ajax({
type: "GET",
url: '?handler=Update&&YourInput=' $(t).val(),
success: function (data) {
$("#div1").html("Your input:" data);
},
error: function (result) {
alert("fail");
}
})
}
</script>
}
handler:
public IActionResult OnGetUpdate()
{
ViewData["YourInput"] = Request.Query["YourInput"];
return Content(ViewData["YourInput"].ToString());
}