簡體   English   中英

使用Razor和AJAX從表單POST返回值

[英]Return a value from a form POST using Razor and AJAX

我有一個簡單的單字段html表單,該表單使用AJAX將值發布到服務器端腳本(用Razor編寫)中。 表單用戶必須猜測一個特定的值,並且將收到一條消息,具體取決於它是否正確。

是否可以使用下面描述的方法返回消息? 理想情況下,我想從服務器端腳本中返回變量“ message”,並在前端向用戶顯示該值。

我的HTML:

<form>
    <input type="text" id="value" name="value" />
    <button>Send</button>
</form>

我的Ajax電話:

$(document).on("click", "button", function(e){
    e.preventDefault(); 

    var dataString = "value=" + $("#value").val();

    $.ajax({
        type: "POST",
        url: "/post",
        data: dataString,
        success: function(data) {
            alert(data.returnedValue);
        }
    });         
});

我的服務器端腳本:

if(IsPost)
{
    string value = Request.Form["value"];
    string message = "";

    if(value.ToString() == "CorrectAnswer"){
        message = "Correct!";
        return message;
    }else{
        message = "Wrong!";
        return message;
    }
}

如果您的服務器頁面是Asp.net頁面(.aspx),則可能需要使用Response.Write

    string value = Request.Form["value"];
    string message = "";

    if(value.ToString() == "CorrectAnswer"){
        message = "Correct!";
        return message;
    }else{
        message = "Wrong!";

    }
   Response.Write(message );

另外,這不會是回發事件。 因此,您無需檢查。

然后在您的腳本中

success: function(data) {
            alert(data);
        }

暫無
暫無

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

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