user1128756
user1128756

Reputation: 79

@Html.ValidationMessageFor crashes when I try to edit an item

Why is my @Html.ValidationMessageFo not working? When I run the application, nothing happens and it allows everything to be entered. And it also crashes when I try to edit an item 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>

Upvotes: 4

Views: 29360

Answers (2)

Bertrand Marron
Bertrand Marron

Reputation: 22210

Here 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, it is a data annotation attribute that specifies that MyProperty is a required field.

MyModel is 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 gets posted to the MyAction action of MyController, the validation of your model will be performed. What you have to do is check whether your model is valid or not. It 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 failed, the view will be rendered again using the different errors that are present in the ModelState object. Those errors will be used and displayed by the ValidationMessageFor helper.

Upvotes: 35

H27studio
H27studio

Reputation: 467

Exactly, Bertrand explains it right, you could also use jquery validation too and eliminate the calls to the server validating on the browser. (asp.net mvc takes care of validating the rules on your model automatically)

Upvotes: 1

Related Questions