Make Label Visible When Validation Visible In Asp.net Mvc
Solution 1:
I don't think you want to do it like that. Why tell them what the error might be when you can tell them what the error actually is?
In your view, after each @Html.EditorFor
put a @Html.ValidationMessageFor
.
@Html.TextAreaFor(a => a.EmailID)
@Html.ValidationMessageFor(a => a.EmailID)
@Html.TextAreaFor(a => a.Password)
@Html.ValidationMessageFor(a => a.Password)
If your model state is invalid and you return to the view, the validation messages are automatically displayed for the invalid fields.
Going further, you can get the validation to be done using JavaScript in the browser, so that if the data is invalid the error message(s) will be displayed without needing a trip back to the server.
Simply add the following to the end of your view:
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
(This assumes your site is based on the standard ASP.NET MVC template, and that you view uses a layout view. If not, you may have to do a bit of tweaking to get the correct JavaScript files.)
WARNING: Never rely solely on browser validation checking. It is there as a benefit to users so they get errors reported slightly faster. However, it is very easy for hackers to bypass browser checking, so always check the model state on the server as well.
Solution 2:
If you want exactly that content, then in your controller, when the model is invalid, put
ViewBag.InvalidModel = true;
Then in your view put
@if(ViewBag.InvalidModel)
{
<!-- Your label here-->
}
Solution 3:
In controller
public ActionResult Index()
{
if (ModelState.IsValid)
{
//do something
return Redirect("/yournewpage");
}
if (!someChecks)
{
ModelState.AddModelError("", "Your custom error");
}
if (!someChecks2)
{
ModelState.AddModelError("", "Your custom error 2");
}
return View();
}
You can use in view
<p>
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<p>
Post a Comment for "Make Label Visible When Validation Visible In Asp.net Mvc"