javascript - 如何在 ASP.NET Core MVC 中将 js 字符串发布到 C#

标签 javascript c# asp.net ajax asp.net-core

我是 ASP 新手,我正在尝试在 JS 代码中获取一个字符串并将其发布到我的 Controller ,以便我可以使用它来查询我的数据库。

JavaScript

function findEmployees(userCounty) {
    $.ajax({
        type: "POST",
        dataType: "json",
        url: '@Url.Action("Index", "Contact")',
        data: JSON.stringify(userCounty),
        contentType: "application/json",
        success: function (response) {
            alert(userCounty);
        },
        error: function (response) {
            alert("failed");
        }
    });
}

Controller

    [HttpPost]
    public ActionResult Index (string userCounty)
    {
        var query = //use linq to query database
        return View(query);
    }

当我在 Controller 中使用 JsonResult 函数时,我只会收到“成功”警报,但我需要它最终将 LINQ 查询返回到 View();函数,但在使用 JsonResult 函数时不起作用。任何想法都会有帮助。如果有更好的方法,我不一定非要使用ajax。我只需要一种方法将存储在 userCounty 中的字符串传递到我的 Controller 。

最佳答案

请像这样更改您的 Controller 方法

[HttpPost]
public ActionResult Index([FromBody]string userCounty)
{
    var query = //use linq to query database
    return View(query);
}

要查看该页面,您需要

[HttpGet]
public ActionResult Index()
{
  return View();
}

关于javascript - 如何在 ASP.NET Core MVC 中将 js 字符串发布到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65221937/

相关文章:

javascript - 如何在单元测试中处理嵌套异步操作

c# - 尝试将数据从 WPF 应用程序发送到任何 Web 浏览器上的网页

c# - 在 ASP.NET 中验证 Oracle 用户

c# - WinRTXamlToolkit.Controls.DataVisualization.Charting 不适用于 .appx bundle

c# - 我们如何将这个Scheme (Lisp) 函数转换为C#

javascript - 如何将值从 View 传递到 MVC ASP .NET 中的另一个 Controller

javascript - 根据选择更改选定值

属性名称上的 Javascript toString 方法

javascript - 打印我的网页时,我可以将标题 'attached' 保留在我的内容中吗?

c# - 为什么 SQLite 插入会非常慢? (使用的交易)