繁体   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