5

I'll try to do the best I can to articulate what I'm trying to do.

Let me preface by saying that I am very new to C# and ASP.NET and have minimal experience with javascript.

I have a javascript function that invokes a prompt box. The overall picture is - if input is entered - it will be saved to a column in the database.

I'm drawing a blank on passing the value from the prompt box to the PostBack in c#.

function newName()
{
    var nName = prompt("New Name", " ");
    if (nName != null)
    {
        if (nName == " ")
        {
            alert("You have to specify the new name.");
            return false;
        }
        else
        {
            // i think i need to getElementByID here???
            //document.forms[0].submit();
        }
    }
}

This is what I have in C#:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //I have other code that works here
    }
    else
    {
        //I'm totally lost here
    }
}

I'm trying to figure out how to make that call for the input from the javascript function.

I've spent the last few hours looking online and in books. Been overwhelmed.

EDIT

i did a little tweeking to fit what I'm trying to do....

<asp:HiddenField ID="txtAction" runat="server" Value="" /> 

document.forms(0).txtAction.Value = "saveevent"; 
document.forms(0).submit();

trying to figure out how to insert the string into the table now.....

 string nEvent = Request.Form["event"]; 
    if (txtAction.Value == "saveevent") { 
                   nName.Insert(); //am i on the right track? 
                 }
rlegs
  • 81
  • 2
  • 11

5 Answers5

2

Well, here's one possible way (untested but should give you the basic idea). You could place a hidden field on your form to hold the value of the prompt:

<input type="hidden" id="hiddenNameField" runat="server" value="">

Then prompt the user for the value, set it to the hidden field, and then submit your form:

document.getElementById('hiddenNameField').value = nName;
document.forms(0).submit();

Then in your code-behind you can just access hiddenNameField.Value.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
0

if you are trying to call the method on the back side using the java script you can try using the web method approach.

for instance you have a function that will call the SendForm method

     function SendForm() {
         var name = $("#label").text();
         PageMethods.SendForm(name,
          OnSucceeded, OnFailed);
     }
     function OnSucceeded() {   
     }
     function OnFailed(error) {
     }

and you have the method that will be called from javascript.

  [WebMethod(enableSession: true)]
    public static void SendForm(string name)
    {

    }

COLD TOLD
  • 13,513
  • 3
  • 35
  • 52
0
<script language='Javascript'> 
__doPostBack('__Page', ''); 
</script> 

Copied from Postback using javascript

Community
  • 1
  • 1
Sandeep Singh Rawat
  • 1,637
  • 1
  • 14
  • 27
0

I think you need AJAX request here. I suggest usage of jQuery, since do the dogs work for you... Otherwise, you will have to implement a lot of already written general code for AJAX processing.

Something as the following one:

function PromptSomewhere(/* some args if needed*/)
{
    var nName = prompt("New Name", " ");
    // Do process your prompt here... as your code in JS above. Not placed here to be more readable.
    // nName is used below in the AJAX request as a data field to be passed.

    $.ajax({
        type: "post", // may be get, put, delete also
        url: 'place-the-url-to-the-page',
        data {
            name: nName
            // You may put also other data
        },
        dataType: "json",
        error: PromptFailed,
        success: OnPromptComplete
    });
}

function  PromptFailed(xhr, txtStatus, thrownErr) // The arguments may be skipped, if you don't need them
{
    // Request error handling and reporting here (404, 500, etc.), for example:
    alert('Some error text...'); // or
    alery(txtStatus); // etc.
}

function OnPromptComplete(res)
{
    if(!res)
        return;

    if(res.code < 0)
    {
        // display some validation errors
        return false;
    }

    // display success dialog, message, or whatever you want

    $("div.status").html(result.message);
}

This will enable you to send dynamically data to the server with asynchronous request. Now C#:

using System.Web.Script.Serialization;

protected void Page_Load(object sender, EventArgs e)
{
    if(IsPostBack && ScriptManager.GetCurrent(this).IsInAsyncPostBack)
    {
        string nName = Request.Form["name"];

        // do validation and storage of accepted value
        // prepare your result object with values 



        result.code = some code for status on the other side
        result.message = 'Some descriptive message to be shown on the page';

        // return json result
        JavaScriptSerializer serializer = new JavaScriptSerializer();

        Response.Write(serializer.Serialize(result));
    }
}

Notes: If you use ASP.NET MVC 2 or higher I think, you will be able to use JsonResult actions and Request.IsAjaxRequest (I think was the name), and many other facilities and improvements of ASP.NET - ASP.NET MVC is the new approach for creating web applications based on MVC pattern (architecture) and will replace ASP.NET Pages eventually in some time.

Rolice
  • 3,063
  • 2
  • 24
  • 32
0

This is a very good resource and contains the answer to your question:

How to use __doPostBack()

Basically, call PostbackWithParameter() function from your other JS function:

<script type="text/javascript">
function PostbackWithParameter(parameter)
{
    __doPostBack(null, parameter)
}
</script>

And in your code-behind, grab the value for that parameter like so:

public void Page_Load(object sender, EventArgs e)
{
    string parameter = Request["__EVENTARGUMENT"];
}
Community
  • 1
  • 1
lkaradashkov
  • 8,609
  • 1
  • 15
  • 12