Validation error message not displaying MVC4

泪湿孤枕 提交于 2019-12-22 10:54:43

问题


I am using MVC4.

Validation is failing but validation error messages are not getting displayed.

This is my model.

public class Configuration
{
    public int Id { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "Site name is required.")]
    [MinLength(6, ErrorMessage = "Name should be at least 6 characters.")]
    public string SiteName { get; set; }
}

Controller.

[HttpPost]
    public ActionResult Create(Configuration configItem)
    {
        if (ModelState.IsValid)
        {
            // do something.
        }
        return View("Index", configItem);
    }

View is

@model Models.SitesConfig.Configuration
@{
ViewBag.Title = "Sites Configurations";
}
<div>
    @Html.ActionLink("Sites List", "List", "SiteConfig")
</div>
@using (Html.BeginForm("Create", "SiteConfig", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <fieldset>
        <legend>New Satellitesite</legend>
        <div>
            @Html.LabelFor(m => m.SiteName, "Name")
            @Html.TextBoxFor(m => m.SiteName)
            @Html.ValidationMessageFor(m=>m.SiteName)
        </div>
        <br />

        <input type="submit" value="Save" />

    </fieldset>
}

Please also suggest me if there is any better way of doing the validations.


回答1:


I don't know what was the problem. After clean and build the application, I am able to see the error message.

Thanks, Naresh




回答2:


There should be @Html.ValidationSummary("Please correct the errors") in the View




回答3:


@using (Html.BeginForm("Create", "SiteConfig", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
  @Html.ValidationSummary()
    <fieldset>
        <legend>New Satellitesite</legend>
        <div>
            @Html.LabelFor(m => m.SiteName, "Name")
            @Html.TextBoxFor(m => m.SiteName)
            @Html.ValidationMessageFor(m=>m.SiteName)
        </div>
        <br />

        <input type="submit" value="Save" />

    </fieldset>
}

Try this one .. @Html.ValidationSummary() helps in displaying the error messages.




回答4:


If you try the above solutions and still didn't work, then maybe you need to format your View file. Go to Edit-Advanced-Format Document. Remember not to be in the debug mode when trying to format your file because you wouldn't see the above listed procedures if you are debugging your project.




回答5:


Make sure your View is referencing the jQuery validations in the Scripts tag -

@section Scripts
{
    @Scripts.Render("~/bundles/jqueryval")
}


来源:https://stackoverflow.com/questions/12298363/validation-error-message-not-displaying-mvc4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!