0

I am trying to get use Javascript to make a prompt for a variable that is then passed to C#. I've read several articles here about how the best way to do this is through a hidden field and getting the value. This works great individually, but get passed over in the C# method (I also read here) that I can run a JS function and a C# method on the same click event. Again, this works fine when I have them separately, but the value is always "" when done together. Here is my code.

Javascript:

function ScheduleName() {
        var inputName = prompt("Schedule name");
        if (inputName.length === 0) {
            alert("Please enter a name.");
            return false;
        }
        document.getElementById('<%=sptext.ClientID %>').innerHTML = inputName;
    }

<asp:Button ID="btnSaveSchedule" OnCLientClick="ScheduleName(); return false;" onclick="btnSaveSchedule_Click" class="btn btn-info" runat="server" Text="Save Schedule"/>

<span id="sptext" runat="server" visible="False"></span>

C#

 protected void btnSaveSchedule_Click(object sender, EventArgs eventArgs)
{
   string scheduleName = sptext.InnerHtml;
}

Those are the pertinentenent parts of the code at least. I've tried calling the C# methods within the Javascript ( function JSFunction() { <%#ProjectName.Csharp.CsharpFunction()%> ; }

I've tried AJAX as well. I am running into some issues where my methods aren't static. Maybe I'm just having a rough time or I truly don't get something fundamental here. I've been programming in Javascript for years but am pretty new to C#. Thank you.

1 Answers1

1

You were well on your way.

First, replace the span with a HiddenField, as the content of a span doesn't get included in the postback data being sent to the server.

<asp:HiddenField runat="server" ID="sptext" />

In your JavaScript set the value of this HiddenField.

function ScheduleName() {
    var inputName = prompt("Schedule name", "");
    if (inputName.length === 0) {
        alert("Please enter a name.");
        return false;
    }
    document.getElementById('<%=sptext.ClientID %>').value = inputName;
    return true;
}

Make sure to return True or Falsevia the Button's OnCLientClick handler depending on whether the given input was valid; use the return value of your clientside script. The postback will only occur in case this script returns True.

<asp:Button ID="btnSaveSchedule" OnCLientClick="return ScheduleName();" onclick="btnSaveSchedule_Click" class="btn btn-info" runat="server" Text="Save Schedule"/>

On serverside, read the value of the HiddenField.

 protected void btnSaveSchedule_Click(object sender, EventArgs eventArgs)
 {
     string scheduleName = sptext.Value;
 }
pfx
  • 20,323
  • 43
  • 37
  • 57