Reputation: 479
I'm pretty new in ASP.NET Razor, and i'm trying to establish a very simple thing, so far unsuccessfully.
I have a button, and input field in the HTML. What i want is to call a C# function with the input field's text, when i click on the button.
I can call the function, but i cannot pass the parameter. How could i refer to the text in this input field?
I have searched on the internet, but i haven't found a simple solution. Are there any? I though something like this one:
<input id="Text1" name="Text1" type="text" />
<input id="Button1" type="button" value="button" onclick="@{Class1.Myfunction(Text1.InnerText);}" />
Thank you!
Edit(solved):
Thanks to Sam's comment, i was able to pass parameters to my C# function in another class. I have put the following code to the top to catch POST params:
@{
if (IsPost)
{
Class1.Myfunction(Request.Form["Text1"]);
}
}
When sending the form from the razor website, it will pass the Text1 field value to the C# function.
<form method="post">
<input id="Text1" name="Text1" type="text" />
<input id="Submit1" type="submit" value="submit" />
</form>
Thanks a lot!
Upvotes: 0
Views: 3400
Reputation: 50728
Once the view renders, the server-side code has completed and any changes the user makes belongs on the client. On posting back, that value will be available in the model and thus you could access the value there and call MyFunction on it then.
Otherwise, you need to use javascript:
<input id="Button1" type="button" value="button" onclick="doSomething(event)" />
And in doSomething (note I use JQuery in my example):
function doSomething(e) {
var text = $("#Text1").val();
//Process it somehow on the client only, not server
}
And then you can do whatever you need in JavaScript; without knowing what MyFunction does. I can't help any further from there...
Upvotes: 0
Reputation: 1985
As far as I know, the only way to call server side functionality is via some kind of HTTP actions like POST or GET. So, you need to do something like:
your_view.cshtml:
<input id="Text1" name="Text1" type="text" />
<input id="Button1" type="button" value="button" />
@section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$('#Button1').on('click', function (event) {
$.ajax({
type: 'GET',
url: <server_side_functionality_URL>,
data: $("#Text1").val(),
success: function (result) {
console.log(result);
},
error: function (errorResult) {
console.log(result);
}
});
});
});
</script>
}
Upvotes: 1