2012-06-07 13 views
5

Cercherò di fare il meglio che posso per articolare ciò che sto cercando di fare.Passare il valore della casella di richiesta dalla funzione javascript- PostBack a C#

Lasciatemi premettere che sono molto nuovo su C# e ASP.NET e ho un'esperienza minima con javascript.

Ho una funzione javascript che richiama una finestra di messaggio. L'immagine generale è - se l'input è inserito - sarà salvato in una colonna nel database.

Sto disegnando uno spazio per passare il valore dalla casella Prompt a 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(); 
     } 
    } 
} 

Questo è quello che ho 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 
    } 
} 

Sto cercando di capire come fare quella chiamata per l'ingresso dalla funzione javascript.

Ho passato le ultime ore a guardare online e nei libri. Stato sopraffatto

EDIT

ho fatto un po 'tweeking per adattarsi quello che sto cercando di fare ....

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

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

cercando di capire come inserire la stringa nella tabella ora ... ..

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

form.sumbmit dovrebbe farlo –

risposta

2

Bene, ecco un modo possibile (non testato ma dovrebbe darvi l'idea di base). Si potrebbe inserire un campo nascosto sul modulo per contenere il valore del prompt:

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

quindi richiedere all'utente per il valore, impostare al campo nascosto, e quindi inviare il modulo:

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

Quindi nel codice code è sufficiente accedere a hiddenNameField.Value.

0

se si sta tentando di chiamare il metodo sul lato posteriore utilizzando lo script java, è possibile provare a utilizzare l'approccio del metodo Web.

per esempio si dispone di una funzione che chiamerà il metodo SendForm

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

e si ha il metodo che verrà chiamato da JavaScript.

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

    } 

0

Penso che è necessario richiesta AJAX qui. Suggerisco l'utilizzo di jQuery, dato che i cani lavorano per te ... Altrimenti, dovrai implementare un sacco di codice generale già scritto per l'elaborazione AJAX.

Qualcosa come la seguente:

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); 
} 

Questo vi permetterà di inviare dinamicamente i dati al server con richiesta asincrona. Ora 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)); 
    } 
} 

Note: Se si utilizza ASP.NET MVC 2 o superiore credo, si sarà in grado di utilizzare le azioni JsonResult e Request.IsAjaxRequest (credo fosse il nome), e molte altre strutture e migliorie di ASP.NET - ASP.NET MVC è il nuovo approccio per la creazione di applicazioni Web basate su pattern MVC (architettura) e sostituirà le pagine ASP.NET in un secondo momento.

0

Questa è una risorsa molto buona e contiene la risposta alla tua domanda:

How to use __doPostBack()

In sostanza, chiamata PostbackWithParameter() funzione dal altra funzione JS:

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

E nel codice Dietro, prendi il valore per quel parametro in questo modo:

public void Page_Load(object sender, EventArgs e) 
{ 
    string parameter = Request["__EVENTARGUMENT"]; 
} 
Problemi correlati