简体   繁体   中英

Get return value from JS code to C#

I want to get the answer of a window.prompt() alert box through the C# Code Behind file. It's just a one-liner of JavaScript code, so I thought I could even execute it from the Code Behind file. It doesn't really matter to me whether it's a <script> tag in the .aspx file or executed through the .aspx.cs file.

I thought of having the script executed (called from the C# part) and then having the return value assigned to a certain not visible field, but is there any better way to do it?

The obvious way would probably go something like this:

.aspx file:
<script>
function foo() {
    document.getElementById('MyFieldID').value = window.prompt('Answer this question:', '');
}
</script>

.aspx.cs file:
////////////////////////////////////////////////
//MyFieldID.Text now contains whatever I want//
//////////////////////////////////////////////

What do you say? Is there any better way?

Better way is always opinion based. What I'd say is you have a few options, all depend on what you're doing. HTTP and ASP.NET provide us a few means of sending data to the server, there are 3 main ones before HTML5:

  1. Query string
  2. Form values
  3. AJAX calls

If you're redirecting the user to a new page after they answer the prompt, you can just send them to yournewurl.aspx?promptAnswer=*whatever*

If you're doing a postback, then you can use a form value (this looks like what you're doing in your example). You can put an <asp:HiddenField> on the page and populate it from JavaScript before submitting the form.

If you need just the prompt response, but are not attempting to reload the page, you can make an AJAX call that sends the variable to the server (this still uses #1 or #2 to send the data, it just does it without reloading the page).

Which of those three options works best depends on your implementation. However, your solution should work just fine. However, since the control you'd likely be using to stuff the value into is a HiddenField it would be in MyFieldID.Value not MyFieldID.Text . The only other thing you have to deal with is if your MyFieldID is nested in some other controls (like a ContentPlaceHolder ) such that the ClientID has naming containers pretended to it so it's really something like ContentPlanceHolder1_MyFieldID when accessed from JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM