c# - 从json控制器结果ajax获取多个字符串
问题描述
我有一个按钮,使用 ajax 从表单中的文本字段向我的 mvc 控制器发送输入。我现在希望控制器将 2 个字符串作为 json 返回,并将这些字符串填充到 html 输入中。
控制器
[HttpPost]
public ActionResult getName(string Name)
{
string SecondString = "secondString";
return Json(Name, SecondString);
}
看法
<script>
$(document).ready(function () {
$("#btnGet").click(function () {
$.ajax(
{
type: "POST",
url: "home/getName",
data: {
Name: $("#txtName").val()
},
success: function (result) {
$('#FirstTextFieldToFill').val(result);
$('#SecondTextFieldToFill').val(result);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
解决方案
您错误地将参数分配Json()
给返回响应的方法JsonResult
,因为第二个参数是JsonRequestBehavior
or contentType
。您应该返回带有单个参数Controller.Json()
的响应,如下所示:
[HttpPost]
public ActionResult GetName(string Name)
{
string SecondString = "secondString";
return Json(new { Name = Name, SecondString = SecondString });
}
然后修改您的 AJAX 调用以使用属性名称从响应中返回 2 个字符串:
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "@Url.Action("GetName", "Home"),
data: { Name: $("#txtName").val() },
success: function (result) {
$('#FirstTextFieldToFill').val(result.Name);
$('#SecondTextFieldToFill').val(result.SecondString);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
推荐阅读
- javascript - javascript:针对元素数组查找元素字符串的出现。出现返回 0
- laravel - 如何在 Cpanel 中为实时服务器安装 gRPC 扩展
- c# - 在 Entity Framework Core 中使用动态过滤器
- node.js - [React-Native]:找不到与 @types/react-test-renderer@16.13.1 匹配的版本
- tcl - Tcl:从 exec bash 获取标准输出
- javascript - 如何将具有 xy 坐标的 JSON 对象转换为 PHP 中的图像?
- javascript - 在 tensorflow.js 中输出 LSTM RNN 的隐藏状态
- android - 在特定时间从应用程序显示 Toast 消息,但应用程序未运行或 klled
- javascript - 页面完全加载后打印页面
- java - 如果不能在静态方法中使用“this”关键字,那么在给定代码中,method1() 如何调用 method2()?