简体   繁体   English

将值从C#传递到JavaScript

[英]Passing value from c# to javascript

I want send a dynamic value from C# to JavaScript. 我想从C#向JavaScript发送动态值。 When I click my button I want to show my value in an alert message. 当我单击按钮时,我想在警报消息中显示我的值。

Here is my C# code : 这是我的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
}

Here is my JavaScript function : 这是我的JavaScript函数:

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

    alert (message);
    // More code here
}

The message is always be null. 该消息始终为空。 I'm already using ViewBag.Collection and I get this value correctly but I cannot get ViewBag.message in JavaScript? 我已经在使用ViewBag.Collection并且可以正确获取此值,但是无法在JavaScript中获取ViewBag.message

Assuming that your JavaScript function is inside your view, you should be able to set the JavaScript variable like this: 假设您的视图中包含JavaScript函数,则应该可以这样设置JavaScript变量:

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

    alert (message);
    // More code here
}

If your function is not inside your view then you can't access the server side ViewBag variable. 如果函数不在视图内,则无法访问服务器端ViewBag变量。 In that case, you'll have to put the variable value in an html data attribute or an html hidden input. 在这种情况下,您必须将变量值放在html数据属性或html隐藏输入中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM