从控制器获取值到Javascript代码

时间:2017-07-25 13:54:08

标签: javascript asp.net-mvc model-view-controller

我从控制器到javascript代码获得Id值,但我想要完整的行值“reportssql.reportName”。并希望通过javascript在视图中显示reportName的值。

这是我的控制器

        [HttpGet]
        public ActionResult ViewReports(int Id, SQLServer_Reports reportssql)
        {
            context = new Cost();
             //Todo get whole row values from ID, right now we have only Report ID
            reportssql.reportName = context.SqlServerReportses.Where(x => x.ReportId == Id).Select(x=>x.reportName).FirstOrDefault();
          //  List<string> report = context.SqlServerReportses.Where(x => x.ReportId == Id).Select(x=>x.reportName).ToList();

            return Json(reportssql.reportName, JsonRequestBehavior.AllowGet);
        }

这是我的javascript函数

 function ViewReport(ID) {
        var id = ID;
        // alert(ID);// getting value from gridview button and passing to javascript alert
        var state = {};
        var newUrl = "/Report/ViewReports/";
        //var newUrl="@Url.Action("ViewReports", "Report")";
        window.history.pushState(state, null, newUrl);
        $.ajax({
            url: newUrl + ID,
            type: "GET",
            success: function () {
                $('#ViewReports').show();
                $('#ShowGrid').hide();
                document.getElementById('lbltipAddedComment').innerHTML = 'Report ID = ' + id;
                // display Report name here
            },
            error: function () {
                bootbox.alert("Error");
            }

        });
       }

就像我在这里显示ID的值一样,但也希望在另一个标签中显示reportName的值。如何获取reportname我的意思         返回Json(reportssql.reportName,JsonRequestBehavior.AllowGet); 在javascript函数中。

1 个答案:

答案 0 :(得分:0)

在success函数中,您需要使用从服务器发送的响应。改变你的成功函数如下:

success: function (reportName) {
    $('#ViewReports').show();
    $('#ShowGrid').hide();
    document.getElementById('lbltipAddedComment').innerHTML = 'Report ID = ' + id;

    // set report name
    $('#lblYourLabelIdHere').text(reportName);
}