开发者

How to show errors on in the view from a fluentvalidation result in a asp.net mvc 2 app?

I am learning asp.net mvc 2 and fluent validation. My setup is shown after the text here. My problem is that I do not know how to set the errors contained in the res object on the view page in a nice way. How should this be done? As it is now no errors are displayed on the view, but the validation is working quite well. I suspect I have to insert some code where I have written "// Set errors on view" in the code. But what code do I need to put? I was not really able to find any clear answers to this - maybe I am just blind. I am looking forward to your help. Thank you.

My controller:

public class AccountController
{
    public ActionResult LogOn()
    {
        return View();
    }

    [HttpPost]
    public ActionResult LogOn(LogOnModel1 model, string returnUrl)
    {
        public class LogOnModel1
        {
            public string UserName { get; set; }
            public string Password { get; set; }
            public bool RememberMe { get; set; }
        }

        public class AccountValidator : AbstractValidator<LogOnModel1>
        {
            public AccountValidator()
            {
                RuleFor(x => x.UserName).NotNull().WithMessage("Brugernavn skal udfyldes").NotEmpty().WithMessage("Brugernavn skal udfyldes");
                RuleFor(x => x.Password).NotNull().WithMessage("Kodeord skal udfyldes").NotEmpty().WithMessage("Kodeord skal udfyldes");
                Custom(x => { return Membership.Provider.ValidateUser(x.UserName,x.Password) ? new ValidationFailure(null, "wrong password") : null; });
            }
        }

        FluentValidation.Results.ValidationResult res = new Models.AccountValidator().Validate(model);
        if (res.IsValid)
        {
            FormsService.SignIn(model.UserName, model.RememberMe);
            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        else
        {
            // Set errors on view
        }
        return View(model);
    }
}

My model and validation class:

public class LogOnModel1
{
    public string UserName { get; set; }
    public string Password { get; set; }
    public bool RememberMe { get; set; }
}

public class AccountValidator : AbstractValidator<LogOnModel1>
{
    public AccountValidator()
    {
        RuleFor(x => x.UserName).NotNull().WithMessage("Brugernavn skal udfyldes").NotEmpty().WithMessage("Brugernavn skal udfyldes");
        RuleFor(x => x.Password).NotNull().WithMessage("Kodeord skal udfyldes").NotEmpty().WithMessage("Kodeord skal udfyldes");
        Custom(x => { return Membership.Provider.ValidateUser(x.UserName,x.Password) ? new ValidationFailure(null, "wrong password") : null; });
    }
}

and finally my view:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TelCountMVC.Models.LogOnModel1>" %>

<asp:Content ID="loginTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Log On
</asp:Content>

<asp:Content ID="loginContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Log On</h2>
    <p>
        Please enter your username and password. <%: Html.ActionLink("Register", "Register") %> if you don't have an account.
    </p>

    <% using (Html.BeginForm()) { %>
        <%: Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.") %>
        <div>
            <fieldset>
                <legend>Account Information</legend>
                <div class="editor-label">
                    <%: Html.LabelFor(m => m.UserName) %>
                </div>
                <div class="editor-field">
                    <%: Html.TextBoxFor(m => m.UserName) %>
                    <%: Html.ValidationMessageFor(m => m.UserName) %>
                </div>
                <div class="editor-label开发者_StackOverflow中文版">
                    <%: Html.LabelFor(m => m.Password) %>
                </div>
                <div class="editor-field">
                    <%: Html.PasswordFor(m => m.Password) %>
                    <%: Html.ValidationMessageFor(m => m.Password) %>
                </div>
                <div class="editor-label">
                    <%: Html.CheckBoxFor(m => m.RememberMe) %>
                    <%: Html.LabelFor(m => m.RememberMe) %>
                </div>
                <p>
                    <input type="submit" value="Log On" />
                </p>
            </fieldset>
        </div>
    <% } %>
</asp:Content>


I suspect that you have figured this out ages ago.

You lose model state if you call RedirectToAction. You have to return a view and pass the LogOnModel1 model into it.

Connect the view to your model instead of System.Web.Mvc.ViewPage and then in your controller do something like this:

if(! ModelState.IsValid) {
     return View("Index", logOnModel1);
}

And here is a link to Jeremy Skinner's (the creator of Fluent Validation) description of how to set it up with MVC 2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜