javascript - 从 MVC 中的 JavaScript 调用带有字符串类型参数的操作
问题描述
我的控制器中有以下操作:
public ActionResult ShowContactTel(string tel)
{
return PartialView("ContactInfoView", tel);
}
我通过 JavaScript 调用上述操作,如下所示:(通过单击按钮触发)
function ShowTel(){
var e="@Model.TelShow";
$.get("ViewProfile/ShowContactTel", e).then(
function (r) {
$('#divTel').innerHTML = r;
});
}
但是动作的输入参数接收空值(通过设置断点),因此返回不需要的输出。
备注1:
我尝试了下面的ShowTel()
函数代码,但结果没有改变:
var str = "@Model.TelShow";
$.ajax({
type: 'GET',
url: '@Url.Content("~/ViewProfile/ShowContactTel")',
data: str,
success: function (dd) {
$('#divTel').innerHTML = dd;
}
});
和
var str = "@Model.TelShow";
$.ajax({
url: "ViewProfile/ShowContactTel",
type: 'GET',
data: str
}).then(function (r) {
$('#divTel').innerHTML = r;
});
我也尝试过type: 'POST'
,但它也不起作用。
备注2:
在函数中使用debugger
命令ShowTel()
,我看到@Model.TelShow
有真正的价值。
问题是什么?
解决方案
您当前的代码(第一种方法)将e
变量的值作为$.get
调用的数据参数传递。jQuery$.get
方法会将其作为查询字符串值发送。因此,您的代码正在像下面的 URL 一样进行 get 调用。
/ViewProfile/howContactTel?testValue
Assuming testValue
is the value of variable e
Your action parameter name is tel
. So send an js object with a property with that name.
Also use the jquery html
method to update the inner html of your div.
$.get("/ViewProfile/ShowContactTel", { tel: e })
.then(function (r){
$('#divTel').html(r);
});
I would also recommend using the Url helper methods to generate the correct relative URLs to the action method.
var url = "@Url.Action("ShowContactTel","ViewProfile");
$.get(url, { tel: e }).then(function (r){
$('#divTel').html(r);
});
推荐阅读
- android - livedata 中的函数观察者不起作用
- json - 在声明自定义 json 名称时初始化结构中的变量返回语法错误:意外文字
- flutter - 使用颤振登录 connectyCube 可能需要 5 到 10 秒
- ios - iOS14 中的 SwiftUI 键盘避免问题和 IgnoresSafeArea 修饰符问题
- jenkins - 詹金斯在 Windows 10 minikube 问题上
- flutter - Flutter 和 Android Studio:找不到 providerinstaller 的本地模块描述符类
- python - 将json文件中的两个字段添加到一个列表中,将两者都变成浮点数,其中一个字段变成负数
- vue.js - 绑定对象属性的更改不会反映在 Vue.js 的 UI 中
- scala - 有没有办法让 scala 代码忽略 ssl 验证?
- c# - 实体框架:当我按确切的日期时间过滤时,出现错误