从视图模型中在asp.net表单构建中实现验证的最简单方法是什么?

时间:2012-08-23 08:21:09

标签: asp.net vb.net validation asp.net-mvc-2

我有一个模型类,我用它来创建表单

Public Class Users
    Public Property Id As Integer
    Public Property UserName As String
    Public Property UserNin As Int16
    Public Property UserType As String
    Public Property Password As String

    Property UserTypes As IEnumerable(Of SelectListItem) = {
            New SelectListItem With {.Value = "admin", .Text = "Admin"},
            New SelectListItem With {.Value = "doctor", .Text = "Doctor"},
            New SelectListItem With {.Value = "reception", .Text = "Receptionist"}
    }
End Class

My View类,使用上面的ViewModel使用HTML Helpers生成表单

<% Using (Html.BeginForm("Create", "User", FormMethod.Post))%>
    <table>
        <tr>
            <td>
                User Name
            </td>
        </tr>
        <tr>
            <td>
                <%= Html.TextBoxFor(Function(x) x.UserName)%>
            </td>
        </tr>
        <tr>
            <td>
                User NIN
            </td>
        </tr>
        <tr>
            <td>
                <%= Html.TextBoxFor(Function(x) x.UserNin)%>
            </td>
        </tr>
        <tr>
            <td>
                Password
            </td>
        </tr>
        <tr>
            <td>
                <%= Html.PasswordFor(Function(x) x.Password)%>
            </td>
        </tr>
        <tr>
            <td>
                <%= Html.DropDownListFor(Function(x) x.UserType, Model.UserTypes)%>
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" value="Add New User" />
            </td>
        </tr>
    </table>
<% End Using%>

现在,为此案例添加验证的最佳方法是什么?


更新

以下是我在另一个案例中尝试的内容,但我仍然没有看到任何验证,操作被调用和处理。

这是我的模型类

Public Class LoginUser
    <Required()>
    Public Property UserName As String

    <Required()>
    <StringLength(8)>
    Public Property Password As String

End Class

这是部分视图

<% Using (Html.BeginForm("Login", "User", FormMethod.Post))%>
<% Html.EnableClientValidation()%>
<table ID="loginTable" runat="server">
    <tr>
        <td>
            <label for="username">UserName</label>
        </td>
    </tr>
    <tr>
        <td>
            <%= Html.TextBoxFor(Function(x) x.UserName)%>
            <%= Html.ValidationMessageFor(Function(x) x.UserName) %>
        </td>
    </tr>
    <tr>
        <td>
            <label for="password">Password</label>
        </td>
    </tr>
    <tr>
        <td>
            <%= Html.TextBoxFor(Function(x) x.Password)%>
            <%= Html.ValidationMessageFor(Function(x) x.Password)%>
        </td>
    </tr>
    <tr>
        <td>
            <input type="submit" value="Login" />
        </td>
    </tr>
</table>
<% End Using%>

登录操作

<HttpPost()>
Function Login() As ActionResult
    If ModelState.IsValid Then
        Dim sql As String
        Dim username As String = Request.Form("username").ToString
        Dim password As String = Request.Form("password").ToString
        Dim dbHelper As New DBHelper(False)

        sql = "SELECT * FROM " & _tblName & " WHERE username = '" & username & "' and password = '" & password & "'"
        Try
            Dim dr As DataRow = dbHelper.ExecuteAndGetRow(sql)

            If Convert.ToInt16(dr.Item(0).ToString) > 0 Then
                Dim nin As String = dr.Item(4)
                Session("loggedin") = 1
                Session("logged") = dr.Item(0)
                Session("logged_nin") = dr.Item(4)
                ViewData("message") = "Login Successful"
                ViewData("show_loginForm") = False
            Else
                ViewData("message") = "Login failed"
                ViewData("show_loginForm") = True
            End If
        Catch ex As Exception
            ViewData("message") = "Login failed"
            ViewData("show_loginForm") = True
        End Try


        Return View()
    Else
        Return View()
    End If
End Function

1 个答案:

答案 0 :(得分:1)

您可以使用数据注释。例如,如果需要UserName字段,则使用<Required>属性对其进行修饰:

<Required>
Public Property UserName As String

并在视图中为错误消息添加了相应的占位符:

<%= Html.TextBoxFor(Function(x) x.UserName) %>
<%= Html.ValidationMessageFor(Function(x) x.UserName) %>

或者如果您想将所有错误消息集中在一个地方,您可以使用ValidationSummary助手:

<%= Html.ValidationSummary() %>

在POST控制器操作中,您可以使用ModelState.IsValid布尔属性验证模型是否有效:

<HttpPost()>
Function Create(model As Users) As ActionResult
    If ModelState.IsValid Then
        ' validation succeeded => do some processing and redirect
        Return RedirectToAction("Create")
    End If

    ' validation failed => redisplay the same view so that the user
    ' can fix the errors
    Return View(model)
End Function

这里有一个article on MSDN,也解释了这一点。