【问题标题】:Some trouble with passing a list of values from a HTML form into a C# method将值列表从 HTML 表单传递到 C# 方法的一些问题
【发布时间】:2012-03-13 13:19:13
【问题描述】:

我正在从数据库中生成许多复选框并将它们呈现在我的 HTML 中。我想要的功能是让用户能够选择多个复选框,该用户的用户 ID 将被传递到 C# 方法中,该方法将运行算法并呈现另一个页面。如何有效地将这些数据传递给我的算法?

到目前为止,这是我的代码:

@{  
    var db = Database.Open("mPlan");
    var sql = "SELECT * from Users";
    var result = db.Query(sql);
 }
<form id="form" name="form" method="post" action="">
    @{foreach (var user in result) {
    <label for="username">@user.Username</label>
    <input type="checkbox" name="@user" id="username" />
    }
    <button type="submit">Add</button>
</form>

【问题讨论】:

    标签: c# asp.net html razor


    【解决方案1】:
    <input type="checkbox" name="userId" value="@user.UserId" />
    

    然后表单应该将 userId 的值作为逗号分隔的列表传递。


    要检索 id 列表,您可以执行以下操作:

    string userIds = Request.Form["userId"]; // get from http post as comma-separated list
    string [] arrUserIds;                    // string array to hold ids
    if (userIds != null)                     // if the userIds isn't null, split into the array
        arrUserIds = userIds.Split(',');
    

    【讨论】:

    • 我怎样才能检索下一个文件中的值?我知道在 PHP 中它会是 $_GET['userID'],你碰巧知道在 c# 中相同的构造是什么吗?例如,如果我想要一个 List 的 UserIds?
    • var userIds = Request.Form["userId"];请参阅上面的编辑答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多