如何在JavaScript ASP.NET MVC视图中更新模型List ?

时间:2021-07-19 04:12:48

I'm using a model that contains a List of string as follows:

我正在使用包含字符串List的模型,如下所示:

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

I want change the value of each string by javscript and then pass data to controller. So I defined list as hidden variable:

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

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

How can I change the _ActivityAccessLevel string in Javascript. I used the following code, but it doesn't work.

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

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

1 个解决方案

#1


0  

You can access the elements by selecting by name, iterating and changing the values like so (with comments):

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

$(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());
    });
});

#1


0  

You can access the elements by selecting by name, iterating and changing the values like so (with comments):

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

$(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());
    });
});