简体   繁体   中英

Passing value from c# to javascript

I want send a dynamic value from C# to JavaScript. When I click my button I want to show my value in an alert message.

Here is my C# code :

[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 :

$('#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?

Assuming that your JavaScript function is inside your view, you should be able to set the JavaScript variable like this:

$('#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. In that case, you'll have to put the variable value in an html data attribute or an html hidden input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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