首页 > 解决方案 > 从 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有真正的价值。

问题是什么?

标签: javascriptasp.net-mvcaction

解决方案


您当前的代码(第一种方法)将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);
});

推荐阅读