繁体   English   中英

如何在MVC C#中为jquery中的ViewBag赋值

[英]How to give a value for ViewBag inside the jquery in mvc c#

我有以下输入字段。

<input class="book_now_modal BClick" type="text" id="destinationFrom_modal" name="destinationFrom_modal" placeholder="@ViewBag.AmritsarList[0].Destination">

我不时地想更改view bag中的值。是否有办法给viewbag项目提供动态值。我尝试使用jquery如下。

  $(".AClick").click(function () {
            //$(".BClick").attr("placeholder"," ");
            var s = parseInt($(this).attr('id'));
            var neededVAl = "@@ViewBag.AmritsarList"+"["+s+"]"+".Destination";
            alert(neededVAl);
            var b = $(".BClick");
            $(this).attr("placeholder",neededVAl);
        });

像这样,我将placeholder替换为警报,它发出@ViewBag.AmritsarList[1].Destination但它没有更改占位符。我该怎么做。

var neededVAl = "@@ViewBag.AmritsarList"+"["+s+"]"+".Destination";

您无法使用上述语句访问ViewBag ,因为它可以在服务器端访问。 您的JavaScript语句在客户端执行,无法直接访问它。

但是,您可以使用Json.Encode方法将数据对象转换为JavaScript Object Notation(JSON)格式的字符串。

var jsObject = @Html.Raw(Json.Encode(ViewBag.AmritsarList));    
$(".AClick").click(function () {        
    var s = parseInt($(this).attr('id'));
    var neededVAl = jsObject[s].Destination;
    alert(neededVAl);
    $(this).attr("placeholder",neededVAl);
});

暂无
暂无

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

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