2

我正在尝试将 JS 变量分配给 ViewBag 属性并在 Html ActionLink 中使用该属性。

但是,我收到了设计时编译错误:getJSON 方法正下方的“语法错误”为@ViewBag.CustomerID = data.CustomerID;

有人可以帮我解决这个问题吗?

这是我的代码:

@Html.ActionLink("Click to edit Customer", "EditCust", "Customer", new { ViewBag.CustomerID }, null);

<script type="text/javascript">

        $(function ()
        {
            var selID = null
            $("#Name").change(function ()
            {
                selID = $("#Name option:selected").val();

                var url = '/Project/SpecificCustomer';
                var param = { Id: selID };
                $.getJSON(url, param, function (data)
                {
                    @ViewBag.CustomerID = data.CustomerID;
                    var html = "<table border='1' cellpadding='3'>";
                    html += "<tr>";
                    html += "<td>" + "Customer ID: " + data.CustomerID + "</td>";
                    html += "</tr>";
                    html += "<tr>";
                    html += "<td>" + "Email: " + data.Email + "</td>";
                    html += "</tr>";
                    html += "<tr>";
                    var FirstName = data.FirstName;
                    FirstName == null ? "" : FirstName;
                    var LastName = data.LastName;
                    LastName == null ? "" : LastName;
                    html += "<td>" + "Name: " + FirstName + " " + LastName + "</td>";
                    html += "</tr>";
                    html += "<tr>";
                    var date1 = new Date(parseInt(data.CreatedDate.substr(6)));
                    date1 == null ? "" : date1;
                    html += "<td>" + "Created: " + date1 + "</td>";
                    html += "</tr>";
                    html += "<tr>";
                    var date2 = new Date(parseInt(data.UpdatedDate.substr(6)));
                    date2 == null ? "" : date2;
                    html += "<td>" + "Updated: " + date2 + "</td>";
                    html += "</tr>";
                    html += "</table>";
                    $("#divData").html('');
                    $("#divData").append(html);
                });
            });
        });

    </script>
4

1 回答 1

5

这行不通。ViewBag 在服务器端工作,当您收到 AJAX 请求的响应时,它将超出范围。收到响应后,您应该使用 JavaScript 更新视图中的值。

您还会收到错误消息,因为分配应该在代码块中:

@{ ViewBag.CustomerID = data.CustomerID; }

然而这仍然行不通,因为 data 是一个 JavaScript 变量。

于 2013-09-22T18:28:21.937 回答