0

I have a query that tests for a valid postcode entry:

using (_ctx)
    {
        try
        {
            var pc = _ctx.tblPostcodes.Where(z => z.Postcode == postcodeOutward)
                .Select(x => new { postcodeId = x.PostcodeID }).Single();
            pcId = pc.postcodeId;
        }
        catch (Exception)
        {
            pcId = 0;
            Response.Redirect("./");
        }
}

I don't like how I've done it. It's clumsy and it doesn't show an error (this is my first MVC project).

I'd rather it return a validation error against the Postcode textbox. I have model annotations for various input mistakes, but have to check the postcode against the database.

Any suggestions on how to set ModelState to get a proper response?

ComfortablyNumb
  • 1,448
  • 10
  • 37
  • 64

1 Answers1

0

You could try:

if(this.ModelState.ContainsKey("postcodeOutward"))
    this.ModelState.Add("postcodeOutward", new ModelState());

ModelState state = this.ModelState["postcodeOutward"];
state.Errors.Add("<error_message>");
state.Value = new ValueProviderResult(postcodeOutward, postcodeOutward == null ? "" : postcodeOutward.ToString(), CultureInfo.CurrentCulture);

You could also try having a custom validation attribute that will perform a check against the database and that should automatically populated the this.ModelState property, but I'm not too sure if accessing the database inside of a validation attribute would be a good/recommened approach to take.

MotoSV
  • 2,348
  • 17
  • 27