Depending on your use case, there are several ways to get the values:
If you need the values in the frontend (e.g. without reload of the page), you can use JavaScript/jQuery to get the values of the textbox. That is because when the user interacts with the inputs, the Razor code already has been executed and turned e.g. into HTML (also see this question). You could set your variables when the inputs are changed using jQuery.change() as follows:
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script type="text/javascript">
var x = null;
var y = null;
$(document).ready(function () {
$("#test").change(function () {
x = $("#test").val();
alert(x);
});
$("#test2").change(function () {
y = $("#test2").val();
alert(y);
});
});
</script>
If it is sufficient to have the values after a reload of the page, you can put the inputs in a form, and submit that to the controller, where the values are available in the request or using model binding (see this tutorial for an example of how to do that in ASP.NET Core MVC). A basic example for your scenario:
In the view:
<form asp-controller="Home" asp-action="Test" method="post">
@Html.TextBox("test")
@Html.TextBox("test2")
<button type="submit">Submit</button>
</form>
And in the Home
controller (note that here you can access the inputs using the Request
):
[HttpPost]
public ActionResult Test()
{
var x = Request.Form["test"].First();
var y = Request.Form["test2"].First();
return RedirectToAction("Index");
}