所以我一直在使用 ASP.NET MVC 5 Web 应用程序,并且正在做一个调查式项目。本质上,用户被问到一个问题,我做了一些格式化,然后我希望数据传回我的 Controller ,以在另一个 View 中提供下一个问题。问题是将数据从 javascript 变量传递到 c# 变量(方法)。这是我的代码:
Javascript:
function validateDateInput() {
var year = $('#yearInput').val();
var month = $('#monthInput').val();
var day = $('#dayInput').val();
//a lot of validation in here to make sure the date is an actual date
goToNextQuestion(month + '/' + day + '/' + year);
}
function goToNextQuestion(output) {
//here is where I need to pass my variable, output, to a c# function in my controller
//I need to call the method submitUserAnswer(output)
}
还有我的 C# 代码:
public void submitUserAnswer(String userOutput) {
//here I take the answer and feed the user the next question, possibly linking to other c# methods
}
所以我最初打算使用 [WebMethod]
,但在那里遇到了一些问题(我是 C# 和 ASP.Net 的新手,一般来说,找不到方法来实现它。出于显而易见的原因,我不能只将变量传递给 ViewBag
,所以我遇到了一个建议调用 jQuery Ajax
的帖子。我从未使用过 Ajax之前。我如何格式化 Ajax 调用来执行我想要的操作,或者是否有另一种更简单的方法来执行相同的操作?
最佳答案
如果您希望使用 AJAX 调用,您可以使用一个简单的 AJAX 将数据发送到您的 Controller 。这会将数据发送到您的 Controller 方法 (subtmitUserAnswer) 并返回数据(响应),您可以使用该数据填充页面。
如果您希望重定向到各种页面/ View ,您不应使用 AJAX,因为 RedirectToAction()
因为 C# ActionResult
不会通过 AJAX 功能。您可以在成功处理程序中使用 window.location.href 移动页面,但是如果您希望根据答案定向到各种 View ,这最适合将模型传递给您的 Controller 并正确使用 MVC。这是基本的 MVC 功能,可以找到更多信息 here或许多在线教程之一。
如果您希望异步,这里是您需要的 AJAX 调用。从后端调用数据/逻辑并保持在同一页面上。
var dateInput = "";
function validateDateInput() {
var year = $('#yearInput').val();
var month = $('#monthInput').val();
var day = $('#dayInput').val();
//a lot of validation in here to make sure the date is an actual date
var dateInput = (month + '/' + day + '/' + year);
$.ajax({
type: "POST",
url: "~/Controllers/controllerName/submitUserAnswer", //Put your path here.
data: { userOutput : dateInput }
success: function (response) {
//Success! Utilize the data sent back in "response" here
}
//add Error handling here
});
}
关于javascript - 格式 $.ajax 调用 asp.net mvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31575946/