我正在尝试将一个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>
答案 0 :(得分:5)
这不起作用。 ViewBag在服务器端工作,当你收到AJAX请求的响应时,它将超出范围。获得响应后,您应该使用JavaScript更新视图中的值。
您也会收到错误,因为作业应该在代码块中:
@{ ViewBag.CustomerID = data.CustomerID; }
然而,这仍然无效,因为数据是一个JavaScript变量。