6

Is there any problem using @Html.ValidationSummary() inside an Ajax.BeginForm form?

I have the following scenario and I can't get validation for required fields. The form is just posted and no error is thrown either.

This is the View:

@using (Ajax.BeginForm("Register", "Account", new AjaxOptions { HttpMethod = "POST", OnSuccess = "closeDialog('RegistroUsuario')" }))
{
   @Html.ValidationSummary() 
   <fieldset>
        <legend>Cadastro novo Usuário</legend>
       <table id="changePassword">
                <tr>
                    <td class="smallField">Username:</td>
                    <td>@Html.TextBoxFor(m => m.UserName)</td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td>@Html.PasswordFor(m => m.Password)</td>
                </tr>
                <tr>
                    <td>Repetir Senha:</td>
                    <td>@Html.PasswordFor(m => m.ConfirmPassword)</td>
                </tr>
                <tr>
                    <td>Email:</td>
                    <td>@Html.TextBoxFor(m => m.Email)</td>
                </tr>
                <tr>
                    <td>Pergunta Secreta:</td>
                    <td>@Html.TextBoxFor(m => m.SecretQuestion)</td>
                </tr>
                               <tr>
                    <td>Resposta:</td>
                    <td>@Html.TextBoxFor(m => m.SecretQuestionPassword)</td>
                </tr>
                <tr>
                    <td>Ativo:</td>
                    <td><input type="checkbox" name="status" id="status" value="Ativo"></td>
                </tr>    
            </table>           
    </fieldset>
    <input type="submit" value="Criar Usuário" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only button-link"/>
}

That´s the Controller:

//
    // POST: /Account/Register
    [HttpPost]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            MembershipProvider mp  = Membership.Provider;
            MembershipCreateStatus Status;                

            // Tenta registrar o usuário
            try
            {
                //Verifica se usuário deve estar ativo ou não no sistema
                if (String.IsNullOrEmpty(Request.Form["status"]))
                {
                    model.Active = false;
                }
                else
                {
                    model.Active = true;
                }

                //Cria o usuário
                MembershipUser newUser = mp.CreateUser(model.UserName, model.Password, model.Email, model.SecretQuestion, model.SecretQuestionPassword, model.Active, Guid.NewGuid(), out Status);

                if (newUser == null)
                {   
                    /**/
                }
                else
                {                       
                    return RedirectToAction("Index", "Home");   
                }

            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

And the Model:

public class RegisterModel
{
    [Required]
    [Display(Name = "Usuário")]
    public string UserName { get; set; }

    [Required]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "A {0} deve ter no mínimo {2} caracteres.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Senha")]
    public string Password { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Repetir Senha")]
    [Compare("Password", ErrorMessage = "As senhas não coincidem")]
    public string ConfirmPassword { get; set; }

    [Required]
    [Display(Name = "Pergunta Secreta")]
    public string SecretQuestion { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "A {0} deve ter no mínimo {2} caracteres.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Senha Pergunta Secreta")]
    public string SecretQuestionPassword { get; set; }

    [Required]
    [Display(Name = "Ativo")]
    public bool Active { get; set; }
}

Am I missing somenthing?

Pete
  • 57,112
  • 28
  • 117
  • 166
Guilherme Longo
  • 2,278
  • 7
  • 44
  • 64
  • Well, what does your debugger tell you? Do you get to the `return View(model)` at all? The Summary looks OK where it is. – H H Nov 20 '12 at 11:13

2 Answers2

7

Found the problem.

The Ajax.Options target id was not set. Once I have set to the validation dom element now I get the messages.

Thanks a lot

Guilherme Longo
  • 2,278
  • 7
  • 44
  • 64
  • What is "validation dom"? When I played with your example I have to set UpdateTargetId to the root element of the view, which you return by Controller and it will rerender it entirely – Philipp Munin Mar 22 '13 at 22:01
  • @Philipp, this is an old project. At that time I was working on that project I had no expertise on what I was doing and I found a solution that I am not sure it was the best one. I´ll open that project at nite and I´ll be back to you with the awnser. – Guilherme Longo Mar 25 '13 at 13:33
3

To be specific on Guilherme Longo Answer

Set AjaxOptions as

new AjaxOptions() { HttpMethod = "Post", OnSuccess = "RefreshMethod", UpdateTargetId = "FormId" }

Notice the UpdateTargetId set to formId. Worked for me Thanks Guilherme

A Coder
  • 3,039
  • 7
  • 58
  • 129
Qazi
  • 66
  • 3
  • "UpdateTargetId" can be set to form parent, not to the form. When it set to the form It works just for the first time. it should be noted that the parent must not have another child. Otherwise, the new code is replaced with the form. – Omid.Hanjani Jun 18 '21 at 19:45