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.