【问题标题】:calling action with string type parameter from JavaScript in MVC从 MVC 中的 JavaScript 调用带有字符串类型参数的操作
【发布时间】:2018-07-13 18:52:01
【问题描述】:

我的控制器中有以下操作:

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;
        });
}

但是 action 的输入参数接收到 null 值(通过设置断点),因此返回了不需要的输出。

备注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:

ShowTel()函数中使用debugger命令,我看到@Model.TelShow有真值。

有什么问题?

【问题讨论】:

    标签: javascript asp.net-mvc action


    【解决方案1】:

    您当前的代码(第一种方法)将e 变量的值作为$.getcall 的数据参数传递。 jQuery $.get 方法会将其作为查询字符串值发送。因此,您的代码会像下面的 URL 一样进行 get 调用。

    /ViewProfile/howContactTel?testValue
    

    假设testValue是变量e的值

    您的操作参数名称是tel。所以发送一个带有该名称的属性的 js 对象。

    还可以使用 jquery html 方法更新 div 的内部 html。

    $.get("/ViewProfile/ShowContactTel", { tel: e })
     .then(function (r){
           $('#divTel').html(r);
      });
    

    我还建议使用 Url 辅助方法来生成操作方法的正确相对 URL。

    var url = "@Url.Action("ShowContactTel","ViewProfile");
    $.get(url, { tel: e }).then(function (r){
        $('#divTel').html(r);
    });
    

    【讨论】:

      猜你喜欢
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多