0

I have this Create view:

 <div class="editor-field">
 @Html.TextBoxFor(model => model.First, new { @id = "id1"})     
 @Html.ValidationMessageFor(model =>model.First)       
 </div>

and a submit button after the TextBox:

<input type="submit" value="Create" />

part of the Model class looks like this:

public int? First { get; set; }

and this is my web.config:

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

So i need to check if value First is already in database before i post this one. If value is already in database add some error.

I understand the part with ModelState.AddModelError but what i cant get arround is this: every time i check for value is null i get result not from the database but it checks if form TextBox is empty or not.

Please help. Thanks in advance.

2 Answers2

0

You are going to need to check this on the server side once the values have been posted.

In this case what you can do is to run the query to check this once the page has already been posted... If your validation condition fails you add the error manually and return the same view. To the client it will look the same as if the error had been picked up by the unobtrusive validation.

I'm not sure how your data layer is setup so I wont go into the specifics on running the query, however, here is how you handle adding validation errors in your controller...

ModelState.AddModelError("First", "Number in Use - Bad User!");

You can then simply return your view as normal and they will be able to see the error/ correct the issue

return View(model);
Kelly Robins
  • 7,168
  • 6
  • 43
  • 66
0

You can in controller check manually with asking db for record with First value. something like:

public ActionResult foo(X x)
{
    var a= /* select where First=x.First */
    if(a!=null)
    {
        ModelState.AddModelError(Params);
    }
    if (ModelState.IsValid)
    /* rest of the code */
}

or

you can create your own custom validator like in this answer: Creating a custom validation through DataAnnotations? another example here: MSDN

Community
  • 1
  • 1
szpic
  • 4,346
  • 15
  • 54
  • 85