javascript - 在MVC中获取从View到Controller的数组属性?

标签 javascript arrays asp.net-mvc

这是我要提交的表格

@using (Html.BeginForm("SigningAsync", "Signing", FormMethod.Post,
    new { onsubmit = "return confirm('Do you really want to submit the form?');"}))
    {
        <div class="col-md-6 col-sm-12 form-group" style="margin-bottom:5px !important">
            <input type="submit"
                   id="btnConf"
                   name="Sign" value="Confirm"
                   class="btn btn-primary pull-right" style="margin-right:2px" />
            <div class="form-group">
                <input type="hidden" id="arr" name="arr" />
            </div>

        </div>
    }

<input type="checkbox" value="@masterData.DocNo" name="selected" class="inforID" id="@masterData.NewDocNo" plant="@masterData.Plant" flowno="@masterData.FlowNo"/>

当选中复选框并按下确认按钮时,我将复选框中的属性输入arr

$(document).ready(function() {
    $("#btnConf").click(function () {

        var selected = [];
        $.each($("input[name='selected']:checked"), function () {
            selected.push({
                DocNo: $(this).val(),
                NewDocNo: $(this).attr("id"),
                Plant: $(this).attr("plant"),
                FlowNo: $(this).attr("flowno")
            });
            document.getElementById("arr").value = JSON.stringify(selected);
        });
        console.log(JSON.stringify(selected));
    });
});

输入arr会像这样

<div class="form-group">
    <input type="hidden" id="arr" name="arr" value="[
        {"DocNo":"100400020719-006","NewDocNo":"ABS-02072019","Plant":"VDNF","FlowNo":"FLW-000001"},
        {"DocNo":"100400020719-007","NewDocNo":"ABS-02072019","Plant":"VDNF","FlowNo":"FLW-000001"}
    ]">
</div>

这就是行动

public async Task<ActionResult> SigningAsync([Bind(Include = "arr")] PurchaseRequestViewModel purchaseRequestViewModel, string Sign, string[] arr)
{
    bool result = false;
    if(arr != null)
    {
        if (ModelState.IsValid && !String.IsNullOrWhiteSpace(Sign))
        {
            for(int i = 0; i < arr.Length; i++)
            {
              string test = a[i].NewDocNo;
            }
        }
    }
}

我无法获取arr中对象的属性,我已尝试string test = a[i][NewDocNo];string test = a[i]["NewDocNo"];. 但这是不对的。如何获取Controller中数组的属性?

我在 Javascript 中尝试过 console.log(selected[0].NewDocNo); ,没问题,但在 Controller 中,就不正确。

最佳答案

HTML 中的值将被视为字符串值,因为没有多个值传递到 Controller 。您仅传递一个值。您需要更改方法签名并使用 string arr 并将值作为字符串。然后在服务器上进行转换。

此外,最好使用 Javascript 和 AJAX 来提交数据,而不是手动提交表单。然后您可以将请求正文中的 arr 值作为 JSON 传递。然后它会自动转换成数组。

关于javascript - 在MVC中获取从View到Controller的数组属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56866225/

相关文章:

javascript - 如何使用 jquery 获取 gridview 中标签的文本值

c - 将字符串解析为空终止数组的最佳方法是什么?

java - 在 Java 中查找字符索引的最佳方法是什么?

php - 我可以使用像 array_map 这样的数组函数设置数组的键吗

c# - 部分 View 中的按钮在搜索后停止工作

c# - 模型类型的强类型 ASP.NET Controller.View() 方法

c# - 谷歌身份验证 OWIN ASP.NET

javascript - 在 Canvas 上移动元素

javascript - 大字体大小的带有 css/javascript 的抗锯齿文本?

javascript - V-不输出