簡體   English   中英

從javascript函數 - PostBack傳遞提示框值到c#

[英]Passing prompt box value from javascript function- PostBack to c#

我會盡我所能來表達我想要做的事情。

讓我先說一下我是C#和ASP.NET的新手,並且對javascript的使用經驗很少。

我有一個調用提示框的javascript函數。 總體情況是 - 如果輸入了輸入 - 它將被保存到數據庫中的一列。

我在將提示框中的值傳遞給c#中的PostBack時畫了一個空白。

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

這就是我在C#中所擁有的:

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

我正在試圖弄清楚如何從javascript函數調用輸入。

我花了最近幾個小時在網上看書。 不堪重負。

編輯

我做了一個小小的推文,以適應我正在嘗試做的事情....

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

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

試圖找出如何將字符串插入表中.....

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

嗯,這是一種可能的方式(未經測試但應該給你基本的想法)。 您可以在表單上放置一個隱藏字段來保存提示的值:

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

然后提示用戶輸入值,將其設置為隱藏字段,然后提交表單:

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

然后在您的代碼隱藏中,您只需訪問hiddenNameField.Value

如果您嘗試使用java腳本在背面調用該方法,則可以嘗試使用Web方法方法。

例如,您有一個將調用SendForm方法的函數

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

你有從javascript調用的方法。

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

    }

<script language='Javascript'> 
__doPostBack('__Page', ''); 
</script> 

使用javascriptPostback復制

我想你在這里需要AJAX請求。 我建議使用jQuery,因為狗會為你工作......否則,你將不得不實現很多已編寫的AJAX處理通用代碼。

有點如下:

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

這將使您能夠使用異步請求將數據動態發送到服務器。 現在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));
    }
}

注意:如果您使用ASP.NET MVC 2或更高版本我認為,您將能夠使用JsonResult操作和Request.IsAjaxRequest (我認為是名稱),以及ASP.NET的許多其他功能和改進 - ASP.NET MVC是基於MVC模式(體系結構)創建Web應用程序的新方法,最終將在一段時間內取代ASP.NET Pages。

這是一個非常好的資源,包含您的問題的答案:

如何使用__doPostBack()

基本上,從你的其他JS函數調用PostbackWithParameter()函數:

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

在您的代碼隱藏中,抓住該參數的值,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM