[英]Passing value from c# to javascript
我想從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
?
假設您的視圖中包含JavaScript函數,則應該可以這樣設置JavaScript變量:
$('#KullaniciBtn').click(function () {
var message = "@Html.Raw(ViewBag.message)";
alert (message);
// More code here
}
如果函數不在視圖內,則無法訪問服務器端ViewBag變量。 在這種情況下,您必須將變量值放在html數據屬性或html隱藏輸入中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.