1

Can anyone give me a nice link to Implement ASP.NET MVC2 validation for my dropdownlist in my view?

My Dropdownlist in my view is something like this:

<%: Html.DropDownListFor(model => model.SelectedStudent, 
                         new SelectList(Model.StudentIDs, "ID", "Name"),
                         "Please select..", 
                         new { id="Student", style = "width:190px;" })%>

and my validation message is:

  <%:Html.ValidationMessageFor(model => model.SelectedStudent) %> 

in my Model I have this validation:

[DisplayName("Student")]
[Required(ErrorMessage="Please Select StudentID.")]
public int Student{ get; set; }

But somehow it's not validating and I am not seeing validation message in my view.

Something causing problem with "Please select"? or please correct me if I am wrong..

Thanks

1 Answer 1

3

In your view, you'll want to put something like this:

<%= Html.ValidationMessageFor(model => model.DropDownListReference) %>

In your model, something like this

public class Whatever
{
    [Required(ErrorMessage = "Please select a Whatever!")]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public int DropDownListReference { get; set; }
}

This is assuming that you just want to validate that they've selected something.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks TreFrog, Do I need to use EnableClientValidation in my view?
If you want the validation to happen via Javascript, yeah. But this way will just render the page if they type in something wrong.
Yes I validated with Javascript its working fine for me.. but I want to try with MVC2 validation.. why its behaving like this.. if my Dropdown list box has Please select its throwing '' value not null value.. is this causing problem?
I changed my example above to better fit what you're talking about. Make sure that the "Please select" option has a value of 0.
but now I am getting Please select value is '' allways.. how to give the Value as 0 in my dropdownlistfor code?
|

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.