【问题标题】:Passing value from c# to javascript将值从 c# 传递到 javascript
【发布时间】:2019-11-24 11:19:47
【问题描述】:

我想将动态值从 C# 发送到 JavaScript。当我单击按钮时,我想在警报消息中显示我的值。

这是我的 C# 代码:

[HttpPost]
[AjaxOnly]
[Authorize(Roles = "DigitalAdmin, DigitalAgency")]
public async Task<ActionResult> YeniKullanici(KullaniciFormModel model)
{
    var yeniKod = SeyahatSaglikController.YeniKod();
    model.KullaniciAdi = ViewBag.Collection;
    var newKullaniciUserName = model.KullaniciAdi + "_" + yeniKod;

    ViewBag.message = newKullaniciUserName;
    // More code here
}

这是我的 JavaScript 函数:

$('#KullaniciBtn').click(function () {
    var message = @Html.Raw(Json.Encode(ViewBag.message));

    alert (message);
    // More code here
}

消息始终为空。我已经在使用 ViewBag.Collection 并且我正确地得到了这个值,但是我无法在 JavaScript 中得到 ViewBag.message

【问题讨论】:

  • 尝试将@Html.Raw(Json.Encode(ViewBag.message)) 放在引号内。
  • 你的意思是像这样的'@Html.Raw(Json.Encode(ViewBag.message))'?
  • 您是否在动态创建 JavaScript 服务器端?因为如果没有,服务器端变量在客户端是不可用的。

标签: javascript c# asp.net-mvc razor


【解决方案1】:

假设您的 JavaScript 函数在您的视图中,您应该能够像这样设置 JavaScript 变量:

$('#KullaniciBtn').click(function () {
    var message = "@Html.Raw(ViewBag.message)";

    alert (message);
    // More code here
}

如果您的函数不在您的视图中,则您无法访问服务器端 ViewBag 变量。在这种情况下,您必须将变量值放入 html 数据属性或 html 隐藏输入中。

【讨论】:

    猜你喜欢
    • 2015-09-19
    • 2014-01-17
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 2016-06-04
    • 2023-03-09
    • 2013-10-26
    • 1970-01-01
    相关资源
    最近更新 更多