Show error message when ModelState is not valid

1

When I submit the form it acknowledges that ModelState.Valid is invalid but when it returns View() does not show the error messages I put in Model .

My Controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Cadastrar(ProdutoCreateModel produtoCreateModel)
    {
        try
        {
            if (ModelState.IsValid)
            {
                  //se a model for valida salvar informações
                 return RedirectToAction("Index", "Produto");
            }
            return View(produtoCreateModel);
        }
        catch (Exception e)
        {
            return RedirectToAction("Index", "Produto");
        }
    }

Part of my View:

@using (Ajax.BeginForm("Cadastrar", "Produto",
                                                new AjaxOptions
                                                {
                                                    HttpMethod = "Post"
                                                }))
                {
                    //Valida o Formulario enviado
                    @Html.AntiForgeryToken()
                    <div class="col-lg-6 col-lg-offset-3">
                        <div style="text-align: center">
                            <input id="imagem" name="imagem" type="file" class="file-loading">
                        </div>
                    </div>
                    <div class="col-lg-12">
                        <div class="form-group">
                            @Html.LabelFor(model => model.Nome)
                            @Html.TextBoxFor(model => model.Nome, new { @class = "form-control " })
                            @Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })
                        </div>
                        <div class="form-group">
                            @Html.LabelFor(model => model.CodigoProduto)
                            @Html.TextBoxFor(model => model.CodigoProduto, new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.CodigoProduto, "", new { @class = "text-danger" })
                        </div>
                        <div class="form-group">
                            @Html.LabelFor(model => model.PrecoPromocional)
                            @Html.TextBoxFor(model => model.PrecoPromocional, new { @class = "form-control" })
                        </div>
                        <div class="form-group">
                            @Html.LabelFor(model => model.CatalogoId)
                            @Html.DropDownList("DropDown", new SelectList(ViewBag.Catalogo, "CatalogoId", "Nome"), "Selecione a categoria", new { @class = "form-control", required = "required" })
                        </div>
                        <button type="submit" style="margin:0 auto" class="btn btn-block btn-lg btn-primary">Salvar</button>
                    </div>
                }

Annotations in my Model:

    [Display(Name = "Nome")]
    [Required(ErrorMessage = "Preencha o nome do produto")]
    [StringLength(1000)]
    public string Nome { get; set; }

I've been reading this would be the way to do it, but when it returns to the view, no message is shown.

I'm using @Ajax.BeginForm , to submit the form.

Thank you in advance.

    
asked by anonymous 17.11.2017 / 13:30

2 answers

2

Complementing @Leonardo Bonneti's response, you should call unobitrusive validation, because when you use @Ajax, you should reload the js functions you need.

Example:

@using (Ajax.BeginForm(
    "Action1",
    "Controller",
    null,
    new AjaxOptions { 
        OnSuccess = "onSuccess",
        UpdateTargetId = "result"
    },
    null)
)
{
    <input type="submit" value="Save" />
}

var onSuccess = function(result) {
    // enable unobtrusive validation for the contents
    // that was injected into the <div id="result"></div> node
    $.validator.unobtrusive.parse($(result));
};
    
17.11.2017 / 14:44
1

Well, by elimination I believe that your problem is the activation of ValidationSummary , because your model is ok, controller ok what this line lacked within your form .

@Html.ValidationSummary(true)

You can put under @Html.AntiForgeryToken()

    
17.11.2017 / 13:39