我的员工模型有名称和公司
我希望能够在一个 CREATE 视图中构建多个员工。我想我需要创建一个IList<Employee>
并执行类似的操作:
<%= Html.TextBoxFor(m => m[0].Name) %>
<%= Html.TextBoxFor(m => m[0].Company) %>
<%= Html.TextBoxFor(m => m[1].Name) %>
<%= Html.TextBoxFor(m => m[1].Company) %>
如果用户点击“添加其他员工”,我希望该视图为新员工制作另一个表单:
<%= Html.TextBoxFor(m => m[3].Name) %>
<%= Html.TextBoxFor(m => m[3].Company) %>
继续添加表单项(如果再次单击它们,则增加数组索引)。
请记住,我需要在create视图中动态构建表单和列表。我还没有填充的员工列表。
我该怎么做?代码示例会很棒,因为我是ASP.NET的新手
答案 0 :(得分:0)
此示例在按钮点击时将项目添加到List(Of T)
,但您可以根据需要将项目添加到控制列表中。
基本上,您创建一个具有多个对象属性的类,以便存储在其中。
然后将项目添加到集合中。
Imports System.Collections.Generic
Partial Class Default2
Inherits System.Web.UI.Page
''# we need to create an array of our control list class
Public Shared _empList As List(Of EmployeeList)
''# button click event
Protected Sub AddStuff
''# create a new employee
Dim emp As Employee = New Employee
With emp
.Name = "Joe"
.Company = "Acme Welding"
End With
''# add the employee to our custom array
_empList.Add(New ControlList(emp))
End Sub
''# this is our custom Employee List
''# the idea behind this is for us to store
Public Class EmployeeList
Private _employee As Employee
Public Property Employee As Employee
Get
Return _employee
End Get
Set(ByVal value As Employee)
_employee = value
End Set
End Property
Public Sub New(ByVal employee As Employee)
_employee = employee
End Sub
End Class
End Class
请注意,您实际上不必使用EmployeeList类来执行此操作,您只需创建一个由L2S / EF等构建的已存在的“Employee”类的列表
然后你将_empList传递给视图并使用foreach循环来迭代它。
沿着这些方向尝试一些事情
public ActionResult ListEmployees()
{
List<Employee> _empList = new List<Employee>();
//'# create a new employee
Employee emp = new Employee();
{
emp.Name = "Joe";
emp.Company = "Acme Welding";
}
//'# add the employee to our custom array
_empList.Add(new emp);
return View(_empList);
}
然后在你看来你会做这样的事情
<%
foreach (var employee in Model)
{
%>
<p>Dude's Name: <%= Html.TextBoxFor(employee.Name) %></p>
<p>Dude's Company: <%= Html.TextBoxFor(employee.Company) %></p>
<%
}
%>