javascript - 格式 $.ajax 调用 asp.net mvc

标签 javascript c# jquery asp.net ajax

所以我一直在使用 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/

相关文章:

c# - 一种避免在构造函数中进行虚拟调用的方法

c# - 从另一个类调用 Main()

javascript - 如何在 MobileFabric 控制台中创建的 Kony Studio 中调用集成服务?

c# - 在哪些 CPU 架构上使用 CLR(和变体)写入 int "implicitly volatile"?

javascript - 从 Jquery/Ajax MODx 调用代码片段

php - 获取当前的 ISO8601 日期/时间戳

jQuery Mobile 面板未关闭

javascript - 如何防止 jquery 全局选择器选择 Polymer 元素之外的内容

javascript - AngularJS:数据绑定(bind)生成空 HTML 标签(Django 冲突)

javascript - 使用 GSAP 制作 SVG 图案变换动画