日期:2014-05-17  浏览次数:20469 次

MVC中的ModelState.IsValid验证总是true
我没有使用强类型视图,ModelState.IsValid验证总是true,感觉好像没有进行Model数据验证
HTML code

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/MasterPage.Master"
    Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Login
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h3>
        用户登录</h3>
    <% using (Html.BeginForm())
       { %>
    <span class="message">
        <%= Html.Encode(ViewData["message"])%>
    </span>
    <div>
        <fieldset>
            <legend>登录信息</legend>
            <div class="editor-label">
                用户名
            </div>
            <div class="editor-field">
                <%= Html.TextBox("username")%>
                <%= Html.ValidationMessage("username")%>
            </div>
            <div class="editor-label">
                密码
            </div>
            <div class="editor-field">
                <%= Html.Password("password")%>
                <%= Html.ValidationMessage("password")%>
            </div>
            <p>
                <input type="submit" value="登录" />
            </p>
        </fieldset>
    </div>
    <% } %>
</asp:Content>


C# code

[HttpPost,ActionName("Login")]
        public ActionResult LoginPost(FormCollection collection)
        {
            userinfo userinfo=new userinfo();
            userinfo.username = collection.GetValue("username").AttemptedValue;
            userinfo.password = collection.GetValue("password").AttemptedValue;
            if (!ModelState.IsValid)
                return View();
            else
            {
                userinfo = dal.Login(userinfo.username, userinfo.password);
                if (userinfo != null)
                {
                    Session.Add("username", userinfo.username);
                    return RedirectToAction("index");
                }
                else
                {
                    ViewData["message"] = "用户名或密码错误,请重新输入!";
                    return View();
                }
            }
        }


哪位高手能帮忙解决一下啊,小弟不胜感激

------解决方案--------------------
userinfo = dal.Login(userinfo.username, userinfo.password);
上面不就是返回数据库中是否有这条记录嘛!
你说是否为空是:输入框中是否为空、还是数据库中没有这条记录?
------解决方案--------------------
他默认值就是true,你没有对模型进行验证,比如如果某个值为空,要添加错误提示