获取输入列表

Raj*_*esh 0 .net c# asp.net webforms .net-4.0

这是html:

<input type="text" value="Google" name="Projects[0]" />
 <input type="text" value="Microsoft" name="Projects[1]" />
 <input type="text" value="Microsoft" name="Projects[2]" />
Run Code Online (Sandbox Code Playgroud)

这也有一个ASPX提交按钮.

<asp:Button ID="submitBtn" Text="Save" runat="server" OnClick="SubmitButton_Click" />
Run Code Online (Sandbox Code Playgroud)

- - C# - - - - - -

 protected void SubmitButton_Click(object sender, EventArgs e)
    {            
        List<string> projectsInCSharp = new List<string>();
        projectsInCSharp.Add(Request["Projects[0]"]); //Google
        projectsInCSharp.Add(Request["Projects[1]"]); //Microsoft

    }
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来执行此操作并自动将其绑定到列表中.例如,在ASP.NET MVC中,您可以执行此操作.但是我正在使用WebForms而我无法切换到MVC.

我使用的是.NET 4.0,C#,ASPX.

Stu*_*tLC 5

这是一个hacky解决方法,但你可以做的是使用浏览器将逗号分隔具有相同name属性的post字段这一事实.

即通过将您的aspx更改为:

<input type="text" value="Google" name="Project" />
<input type="text" value="Microsoft" name="Project" />
<input type="text" value="Oracle" name="Project" />
Run Code Online (Sandbox Code Playgroud)

然后,您可以在Code Behind中执行一个班轮:

List<string> projectsInCSharp = Request["Project"].Split(',').ToList();
Run Code Online (Sandbox Code Playgroud)


Iva*_*n G 5

试试这段代码,您可以使用AddRange而不是多次调用Add:

        List<string> projectsInCSharp = new List<string>();
        projectsInCSharp.AddRange(Request.Params
            .Cast<string>()
            .Where(o => o.StartsWith("Projects["))
            .OrderBy(o => int.Parse(o.Remove(o.Length - 1, 1).Remove(0, 9)))
            .Select(o => Request.Params[o])
            );
Run Code Online (Sandbox Code Playgroud)

或者你可以把它放在一个构造函数中:

        List<string> projectsInCSharp = new List<string>(
            Request.Params
                .Cast<string>()
                .Where(o => o.StartsWith("Projects["))
                .OrderBy(o => int.Parse(o.Remove(o.Length - 1, 1).Remove(0, 9)))
                .Select(o => Request.Params[o])
            );
Run Code Online (Sandbox Code Playgroud)