1

I have a View:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <div class="input-group">
            <div class="input-group-addon">
                @Html.Label("Employee number", new { @class = "control-label" })
            </div>
            <div class="a">
                @Html.TextBoxFor(model => model.EmployeeNo, new {@class="form-control" })
                @Html.ValidationMessageFor(model => model.EmployeeNo)
            </div>
        </div>
       /*
       * other fields
       */
}

and Controller:

[HttpPost]
public ActionResult Edit([Bind(Include="Id,EmployeeNo,Name,Surname,ContactInfo,RoleId")] User user)
{
    ValidateRequestHeader(Request);
    if (ModelState.IsValid)
    {
        unitOfWork.userRepository.Update(user);
        unitOfWork.Save();
        return Json(new { ok = true, newurl = Url.Action("Index") });
    }
    //ModelState.AddModelError("", "Niepoprawne dane");
    ViewBag.RoleId = new SelectList(unitOfWork.roleRepository.Get(), "Id", "RoleName", user.RoleId);
    return PartialView(user);
}

and model:

public partial class User
{
    public User()
    {
        this.DeviceUsages = new HashSet<DeviceUsage>();
    }

    public int Id { get; set; }
    [Required(ErrorMessage="Brak numeru pracownika")]
    public string EmployeeNo { get; set; }
    [Required(ErrorMessage = "Brak imienia")]
    public string Name { get; set; }
    [Required(ErrorMessage = "Brak nazwiska")]
    public string Surname { get; set; }
    [Required(ErrorMessage = "Brak Adresu email")]
    public string ContactInfo { get; set; }
    public int RoleId { get; set; }
}

Data annotations are working. If I leave eg. Name empty ModelState is not Valid in controler. But validation messages are not shown. If I uncomment this line: ModelState.AddModelError("", "Niepoprawne dane"); this will be the only Model error shown in the View.

Where is a mistake in my code?

Xaruth
  • 4,034
  • 3
  • 19
  • 26
szpic
  • 4,346
  • 15
  • 54
  • 85

1 Answers1

3

It's because you are using @Html.ValidationSummary(true) means excludePropertyErrors = true

x2.
  • 9,554
  • 6
  • 41
  • 62
  • Ok but in this [answer](http://stackoverflow.com/questions/8635406/html-validationsummarytrue-whats-the-true-do) They said that true=show `model level error` Errors thrown by model annotations aren't model lvl errors? – szpic Mar 11 '14 at 09:55
  • 1
    model level errors are errors without name. Errors thorwn by model annotations are property level errors – x2. Mar 11 '14 at 09:59