1

I have the following models:

class Identity
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

class Person
{
    public Identity Identity { get; set; }
}

Now I want to add a validation model error to the surname in my controller:

[HttpPost]
public ActionResult CreatePerson(Person person)
{
   // some validation stuff
   ModelState.AddModelError("Identity.Surname", "Surname has not been found in BBDD");
                             ^^^^^^^^^^^^^^^^
}

How must I refer to the surname inside the Identity object to show the validation error correctly in my view?

I show the validation error in the view as:

@Html.ValidationMessageFor(model => model.Identity.Surname)

But the error is shown in the general validation summary.

8
  • Whats the name of the property in class Person - public Identity WhatName { get; set; }! Commented Oct 23, 2014 at 9:23
  • Sorry, It was mispelled, updated. Commented Oct 23, 2014 at 9:30
  • Then ModelState.AddModelError("Identity.Surname", "...) is correct - assuming you view has @Html.ValidationMessageFor(m => m.Identity.Surname). Commented Oct 23, 2014 at 9:35
  • @StephenMuecke: Mmmm I see, it's not really working, I don't know why Commented Oct 23, 2014 at 9:37
  • possible duplicate: stackoverflow.com/questions/15504348/… Commented Oct 23, 2014 at 9:38

1 Answer 1

1

you can try to implement Remote attribute to your Surname property. It will allow you to perform validation on client side using ajax to check whatever you want on server. Here is documentation.

class Identity
{
    public string Name { get; set; }
    [Remote("CheckSurname", "Validation")]
    public string Surname { get; set; }
}

public class ValidationController : Controller {

    public JsonResult CheckSurname(string Surname) {

        if(/*your busines logic*/) {
            return Json(true, JsonRequestBehavior.AllowGet);
        }
        else {
            return Json("Your error message here", JsonRequestBehavior.AllowGet);
        } 

    }
}

in web.config you should enable this:

<appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Sign up to request clarification or add additional context in comments.

3 Comments

Nice suggestion, but not an answer to the question
@StephenMuecke just another way to do ops task. He wants error page? He can get it without posting a form.
It does not answer OP's question which is how to add a ModelState error in the controller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.