Show error message when Modelstate is not valid

Asked

Viewed 537 times

1

When I submit the form it recognizes that the ModelState.Valid is invalid but when it returns to 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; }

From what I’ve been reading this would be the way to do, but when you return to the view, no message is shown.

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

Thank you very much.

  • William, you’d have to post the entire body of the form?

  • Yes, just a moment

2 answers

2


Complementing the @Leonardo Bonneti response, you should call the 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));
};
  • Very interesting, I’ll try here.

1

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

@Html.ValidationSummary(true)

You can put it under @Html.AntiForgeryToken()

  • I added this line of code but it didn’t work, I switched to @Ajax.BeginForm for @Html.BeginForm and it worked, I think it was a misunderstanding of the functionalities of these methods.

  • I imagined it, but how @Ajax.BeginForm is a method of MVC itself I thought would work, however good. The @Html.ValidationSummary(true) resolved? dps take a look if it works without it just to make doubt.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.