[英]Return a value from a form POST using Razor and AJAX
I have a simple, one-field html form of which I'm posting the value to a server side script (written in Razor) using AJAX. 我有一个简单的单字段html表单,该表单使用AJAX将值发布到服务器端脚本(用Razor编写)中。 The form user has to guess a particular value and will receive a message depending if it's correct or not.
表单用户必须猜测一个特定的值,并且将收到一条消息,具体取决于它是否正确。
Is it possible to return a message using the method described below? 是否可以使用下面描述的方法返回消息? Ideally I would like to return the variable "message" from my server-side script and display the value to the user on the front end.
理想情况下,我想从服务器端脚本中返回变量“ message”,并在前端向用户显示该值。
My HTML: 我的HTML:
<form>
<input type="text" id="value" name="value" />
<button>Send</button>
</form>
My Ajax call: 我的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);
}
});
});
My server-side script: 我的服务器端脚本:
if(IsPost)
{
string value = Request.Form["value"];
string message = "";
if(value.ToString() == "CorrectAnswer"){
message = "Correct!";
return message;
}else{
message = "Wrong!";
return message;
}
}
If your server page is an Asp.net page (.aspx), you probably need to use Response.Write
如果您的服务器页面是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 );
Also, This is not going to be a postback event. 另外,这不会是回发事件。 So you do not need to check that.
因此,您无需检查。
and in your script, 然后在您的脚本中
success: function(data) {
alert(data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.