【问题标题】:How do I update a model List<string> in JavaScript ASP.NET MVC view?如何在 JavaScript ASP.NET MVC 视图中更新模型 List<string>?
【发布时间】:2018-09-10 05:44:46
【问题描述】:

我正在使用一个包含如下字符串列表的模型:

 public List<string> _ActivityAccessLevel { get; set; }

我想通过 javscript 更改每个字符串的值,然后将数据传递给控制器​​。 所以我将列表定义为隐藏变量:

for (int i = 0; i < 100; i++)
{
    @Html.HiddenFor(model => Model._ActivityAccessLevel[i])
}

如何在 Javascript 中更改 _ActivityAccessLevel 字符串。我使用了以下代码,但它不起作用。

$("#_ActivityAccessLevel" + '[' + cuurentID + ']').val(cuurentID +100);

【问题讨论】:

  • 查看您的代码生成的 html! - 它的id="_ActivityAccessLevel_#_"(其中# 是索引器)
  • 但是你也可以给你的输入一个类名,然后使用$(yourClassName).eq(cuurentID).vall(....);
  • 正如我复制的一样,页面源中没有生成任何其他内容
  • 因此没有 id 属性 - 您需要添加一个或使用 [name=".."] 选择器(或者最好使用我的第二条评论中的代码)

标签: javascript asp.net-mvc view parameter-passing


【解决方案1】:

您可以通过按名称选择、迭代和更改值来访问元素(使用 cmets):

$(function () {
    // Select all the elements with name starting with "_ActivityAccessLevel["
    var accessLevels = $("[name^='_ActivityAccessLevel[']");
    // Iterate the elements and change the value to value_100 (or a value of your choice)
    $.each(accessLevels, function () {
        $(this).val($(this).val() + "_" + 100);
    });
    // This is just to check that the values have actually changed in the DOM
    // as the value won't be changed in the html inspector
    // **This should be removed after checking**
    $.each(accessLevels, function () {
        console.log("+++++> " + $(this).attr("name") + " => " + $(this).val());
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 2013-01-21
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多