c# - 如何在 mvc c# 中的 jquery 中为 ViewBag 赋值

标签 c# jquery asp.net-mvc

我有以下输入字段。

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

有时我想更改 View 包内的值。有没有办法为 View 包项目提供动态值。我已经尝试使用 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 对象表示法 (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);
});

关于c# - 如何在 mvc c# 中的 jquery 中为 ViewBag 赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36566005/

相关文章:

asp.net-mvc - ASP.NET MVC - 将 Controller 和相关 View 放在同一个文件夹中?

c# - Controller 返回列表对象的类型名称而不是列表中的内容

C# 编译器不会优化不必要的转换

c# - 如何在没有 WSE 的情况下使用 SOAP 在 .NET 中签署 Amazon Web 服务请求

javascript - Masked 为单个输入文本框编辑两种代码格式

javascript - 输入聚焦时的 jQuery.HotKeys 键绑定(bind)

javascript - 错误时从 AJAX 调用重定向到 View

c# - 使用 while 循环取消查询永远挂起

c# - 为什么我们使用时间跨度从另一个日期减去一个日期时得到负值

jQuery (函数(a){...})(jQuery);