在 javascript 中分配 ViewBag 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18947298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assigning ViewBag property in javascript
提问by sagesky36
I am trying to assign a JS variable to a ViewBag property and use that property in an Html ActionLink.
我正在尝试将 JS 变量分配给 ViewBag 属性并在 Html ActionLink 中使用该属性。
However, I'm getting a design time compile error: "Syntax error" right below the getJSON method as @ViewBag.CustomerID = data.CustomerID;
但是,我收到了一个设计时编译错误:getJSON 方法正下方的“语法错误”为 @ViewBag.CustomerID = data.CustomerID;
Can someone help me out with how this is done?
有人可以帮我解决这个问题吗?
Here is my code:
这是我的代码:
@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>
回答by Ufuk Hac?o?ullar?
This won't work. ViewBag works on server side and it will be out of scope when you get the response of an AJAX request. You should use JavaScript to update the values in your view once you get the response.
这行不通。ViewBag 在服务器端工作,当您获得 AJAX 请求的响应时,它将超出范围。获得响应后,您应该使用 JavaScript 更新视图中的值。
You also get the error because an assignment should be in a code block:
您还会收到错误,因为分配应该在代码块中:
@{ ViewBag.CustomerID = data.CustomerID; }
However this still won't work because data is a JavaScript variable.
但是这仍然不起作用,因为 data 是一个 JavaScript 变量。