Sasha
Sasha

Reputation: 1

MVC - Data annotations for controls

Can you please explain how to apply data annotations to custom control?

Example: Model

public class ToDo
{
    [Required]
    public int ListId { get; set; }
}

View

<form action="/Todo/Submit" method="post">
    <input type="text" name="txtListId" /><br />
    <input type="submit" name="btnSubmit" />
</form>

How can I ensure that data annotation is used when user doesn't enter anything in txtListId?

I know that in my custom model binder - I can either use bindingcontext.valueprovider to get attemptedvalue and check if it is nullorempty and add error to modelstate or use try - catch block to catch formatexception and invalidate modelstate.

But in above methods - data annotation is not really used.

Please guide me in this regard.

Thank you, Sasha

Upvotes: 0

Views: 198

Answers (2)

AnkitMittal
AnkitMittal

Reputation: 164

To display the validation message, assuming that you are using Razor view engine and your view is bound to the model Todo, you must use the following line:

<%= Html.ValidationMessageFor(m=>m.ListId) %>

This will cause the validation message to be displayed on the page. Hence, your view must look something like this:

@Html.TextBoxFor(m => m.ListId)
<%= Html.ValidationMessageFor(m=>m.ListId) %>

Also, in the controller, you need to have a check for validating the model state:

if (ModelState.IsValid)
{
    //take some action
    //maybe, add to DB or whatever
}
else
    return view(); // render the view again

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239200

Using the right field would be a good start. You've specified that ListId is required, but you're never using ListId, but rather txtListId. You should really use Razor helpers to generate your inputs:

@Html.TextBoxFor(m => m.ListId)

Short of that, just name your input properly:

<input type="text" name="ListId" />

Upvotes: 1

Related Questions