【问题标题】:Passing a dynamic list through POST in asp.net c#在asp.net c#中通过POST传递动态列表
【发布时间】:2016-06-21 09:26:53
【问题描述】:

在我看来,我需要多个输入框来输入动态数量的值。例如,如果我有动态数量的输入框(此处显示http://jsfiddle.net/skip405/9sX6X/6/)。我如何将所有这些值传递给我的控制器?

目前,我的视图中有一个输入框,设置如下:

<div class="col-md-10">
    @Html.TextBoxFor(m => m.StudentName, new { @class = "form-control", @id = "current", @name = "content" })
</div>

我的模型这样定义 StudentName:

[Required]
[Display(Name = "Student name")]
public string StudentName { get; set; }

我的第一个想法是在模型中设置一个数组并在其中存储每个数据项,尽管我没有 ASP.NET 或 C# 方面的专业知识来执行此操作。

提前致谢!

【问题讨论】:

  • 不确定您的问题是什么,您也可以添加 asp.net-mvc 标签,因为它看起来像是在使用 ASP.NET MVC。
  • 如果您想动态添加收藏项,请参阅答案herehere 以获取一些示例。并且在使用 HtmlHelper 方法时不要尝试设置 name 属性(无论如何它都不能正常工作)并使用 new { id = "" } 删除 id 属性,否则您将拥有重复的 id 属性(这是无效的html)

标签: javascript c# asp.net-mvc


【解决方案1】:

在控制器中将数据从请求转换为动作输入参数的过程称为模型绑定。这里实现了很大的灵活性,见Model Binding To A List

基本思想是,如果您有多个同名输入,它们可以绑定到List&lt;string&gt;

更复杂的场景也是可能的:如果你喜欢

public class Person
{
    public int Age{get; set;}
    public string Name{get; set;}
}

还有一个动作方法:

public ActionResult DoSomething(List<Person> people)
{
     //do something
}

输入字段可以是这样的:

<input type="number" name="[0].Age" />
<input type="number" name="[0].Name" />
<input type="number" name="[1].Age" />
<input type="number" name="[1].Name" />

【讨论】:

  • 作为一个仅链接的答案,我认为这应该是一个评论。
  • 这似乎是最好的解决方案,但我需要找到一种有效的方法来命名新输入框以适应列表的索引。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多