验证MVC中的多个实体创建

时间:2013-12-17 21:23:53

标签: asp.net-mvc entity-framework validation asp.net-mvc-4

此处的目标是允许用户填写时间表。单个时间实体由以下模型(简化)表示:

Public Class ppTimeItem
    <Key()>
    Public Property TimeItemID As Integer

    // fields that will be entered only once (global)
    Public Property TaskID As Integer
    Public Property EmployeeID As Integer
    Public Property HourlyRate As Decimal

    // fields that can be entered multiple times (see below)
    Public Property ActivityDate As Date
    Public Property HoursWorked As Decimal
    Public Property Billable As Boolean
    Public Property Notes As String
End Class

但是,因为用户必须能够同时提交多个时间实体,所以我使用的是具有多个全局字段的模型(用户只需要输入一次,这将适用于所有时间实体)和一个集合个人时间实体:

Public Class TimesheetTaskModel
    // fields that will be applied to every ppTimeItem in the collection
    Public Property TaskID As Integer
    Public Property EmployeeID As Integer
    Public Property HourlyRate As Integer

    Public Property times As IEnumerable(Of ppTimeItem)
End Class

这样,用户只需要输入一次某些字段,这将适用于集合中的每个时间实体。这就是用户必须填写的时间表:

@Html.HiddenFor(Function(model) model.TaskID)
@Html.DropDownList("EmployeeID", String.Empty)
@Html.EditorFor(Function(model) model.HourlyRate)

...
<tr>
    <td>1.</td>
    <td><input type="text" name="times[0].ActivityDate" /></td>
    <td><input type="text" name="times[0].HoursWorked" /></td>
    <td><input type="checkbox" name="times[0].Billable" /></td>
    <td><input type="text" name="times[0].Notes" /></td>
</tr>
<tr>
    <td>2.</td>
    <td><input type="text" name="times[1].ActivityDate" /></td>
    <td><input type="text" name="times[1].HoursWorked" /></td>
    <td><input type="checkbox" name="times[1].Billable" /></td>
    <td><input type="text" name="times[1].Notes" /></td>
</tr>
...

填写完字段并提交表单后,控制器需要处理验证。这是我有点卡住的地方。通常只有一个实体,我可以称之为......

<HttpPost()>
Function CreateEntity(ent As TheEntity) As ActionResult
    If ModelState.IsValid Then
        // Add single entity to database
        // Save database changes
        // Return Redirect
    Else
        // Return View(ent)
    End If
End Function

...在验证失败的情况下,实体只返回到视图,仍然显示先前输入的所有字段,并且所有验证错误都以红色突出显示。简单的默认值。

创建多个实体时,这不起作用。当我将TimesheetTaskModel返回到视图时,没有保存先前输入的字段,也不会显示验证错误。我如何验证每个时间实体?我真的在寻找符合......的方式......

<HttpPost()>
Function CreateTimeItems(ttm As TimesheetTaskModel) As ActionResult
    For Each ti as ppTimeItem in ttm.times
        // If ti does not have valid model state
            // Return View(ttm)  <-- Needs to show errors
        // End If

        // If all items had valid model state, add each to the database
    Next
End Function

由于

0 个答案:

没有答案