@ Html.ValidationMessageFor not working

Hi guys, I looked at google, yahoo and couldn’t find the answer to the question why is this mine'@Html.ValidationMessageFor not working. 'When I launch the application, nothing happens, it allows you to enter everything. And it also crashes when I try to edit an element in my edit view, which is below. I have the following:

<div class="editor-label"> @* @Html.LabelFor(model => model.Posted)*@ </div> <div class="editor-field"> @Html.HiddenFor(model => model.Posted, Model.Posted = DateTime.Now) @Html.ValidationMessageFor(model => model.sendinghome) </div> <div class="editor-label"> @Html.LabelFor(model => model.Cartypes) </div> <div class="editor-field"> @Html.EditorFor(model => model.Cartypes) @Html.ValidationMessageFor(model => model.Cartypes) </div> <div class="editor-label"> @Html.LabelFor(model => model.RegNum) </div> <div class="editor-field"> @Html.EditorFor(model => model.RegNum) @Html.ValidationMessageFor(model => model.RegNum) </div> <div class="editor-label"> @Html.LabelFor(model => model.Regprice) </div> <div class="editor-field"> @Html.EditorFor(model => model.Image) @Html.ValidationMessageFor(model => model.Regprice) </div> 
+4
source share
2 answers

This is how validation works.

Let's say you have the following model:

 public class MyModel { [Required] public string MyProperty { get; set; } } 

Note the Required attribute, which is a data annotation attribute that indicates that MyProperty is required.

MyModel used by the following view (MyView.cshtml):

 @model MyNamespace.MyModel @using (Html.BeginForm("MyAction", "MyController")) { @Html.LabelFor(m => m.MyProperty) @Html.TextBoxFor(m => m.MyProperty) @Html.ValidationMessageFor(m => m.MyProperty) <input type="submit" value="Click me"> } 

Then, when this form is submitted to the MyAction MyController action, your model will be validated. You need to check if your model is valid or not. This can be done using the ModelState.IsValid property.

 [HttpPost] public ActionResult MyAction(MyModel model) { if (ModelState.IsValid) { // save to db, for instance return RedirectToAction("AnotherAction"); } // model is not valid return View("MyView", model); } 

If the validation fails, the view will be displayed again using various errors that are present in the ModelState . These errors will be used and displayed by the ValidationMessageFor helper.

+29
source

Exactly Bertrand is explaining this correctly, you can also use jquery validation and exclude calls to the server validating the browser. (asp.net mvc automatically checks the rules on your model)

+1
source

Source: https://habr.com/ru/post/1389366/


All Articles