我是 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/