How to send error or info messages to the view with ModelState?

0

I have the following form with Ajax.BeginForm

using (Ajax.BeginForm("MiAccion", "MiController", new { ReturnUrl = ViewBag.ReturnUrl }, new AjaxOptions
    {
        OnSuccess = "OnSuccess",
        OnFailure = "OnFailure"
    }))
    {
        @Html.AntiForgeryToken()

        <div class="SigninX-Main-Title">
            <h1>Iniciar Sesión</h1>
            <p>Ir a Sucursal virtual</p>
        </div>
        <div class="SigninX-Main-Field u-pad-T-1">
            <div class="SigninX-Main-Field-Inputs u-pad-T-1">
                <div class="col-12 u-no-pad">
                    <div class="input-field">
                        @Html.EditorFor(m => m.UserName, new { @class = "validate" })
                        @Html.LabelFor(m => m.UserName)
                        @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "red-text" })
                    </div>
                    <div class="input-field">
                        @Html.EditorFor(m => m.Password, new { @class = "validate" })
                        @Html.LabelFor(m => m.Password)
                        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "red-text" })
                    </div>

                        <button type="submit" class="btn waves-effect waves-light">Siguiente</button>

                    </div>
                }

My controller

[HttpPost]
public ActionResult MiAccion(LoginViewModel model)
{
    ViewBag.Message = "Mi Titulo";

    if (!ModelState.IsValid)
       return View(model);

    if (model.UserName == "miusuario")
        ModelState.AddModelError("UserName", "Ups, ocurrio un error");

    return View();
}

But it does not print the error message in my view. I was reading that it is due to the event functions OnSucces and OnFailure of 'Ajax.BeginForm. Does anyone know how to handle this so that the message appears in the view?

It should be mentioned that if the form is changed to a normal one (without ajax) it works.

    
asked by vcasas 21.06.2018 в 19:31
source

1 answer

-1

I think the only thing you need is to put the following line of code in the view next to @Html.AntiForgeryToken() :

@Html.ValidationSummary(true) 

With that it should work.

    
answered by 25.06.2018 в 20:13