简体   繁体   中英

How to display annotation MVC 4

I'm new in MVC 4 and I'm struggling to displaying the error message for the required field. please help

this is in my model.

[Required(ErrorMessage="Required Field")]
public string Username { get; set; }

[Required(ErrorMessage = "Required Field")]
public string Password { get; set; }

this is in my view

@using (Html.BeginForm("AddUser","User", FormMethod.Post))
{

    @Html.DisplayNameFor(l => l.Username)
    @Html.TextBoxFor(c => c.Username)
    @Html.ValidationMessageFor(c => c.Username);
    <br />
    @Html.LabelFor(l => l.Password)
    @Html.TextBoxFor(c => c.Password)
    @Html.ValidationMessageFor(c => c.Password)
}

thanks in advance

Please whether you have included the necessary javascript files for unobtrusive validation in the right order and that will make the validation happen successfully at the client-side.

jquery.js
jquery.validate.min.js
jquery.validate.unobtrusive.min.js

Regarding the server side validation you have to save the model to the database by explicitly checking ModelState.IsValid .

I suppose you are taking about client validation because it looks like your server validation should work.

Are you loading the correct scripts for client validation?

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")

Also make sure these settings are in your web.config

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

in addition to you model annotations you need to reference jquery validation library to your page for client side validation.

jquery.js
jquery.validate.js
jquery.validate.unobtrusive.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM