Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, March 12, 2015 4:58 AM
Hi,
Im new to MVC, my aim is to create a dropdownlist, with model validation.
I have a database with multiple columns i was to display only one unique value from that column and not multiple of the same one.
e.g. column "age" the data could be 21, 24, 21, 22, 21
I would only like to show 21 once in the dropdownlist.
This is what i have done so far
Controller
public ActionResult Index(string age)
{
var AgeLst = new List<string>();
var AgeQry = from r in db.table1
orderby r.age
select r.age;
AgeLst.AddRange(AgeQry.Distinct());
ViewBag.age = new SelectList(AgeLst);
}
View
<p>Age: @Html.DropDownList("age")</p>
I want to add some validation to the dropdownlist to make it a required field, im not sure if what ive shown above is best practice but I have used a Model view before to allow validation but not sure how to go about this.
Hope what i have posted is clear but if you need more information please let me know.
How do i add a Model so i can add in - [required]
All replies (3)
Monday, March 16, 2015 1:46 AM âś…Answered
Hi
Thanks for your post.
Please refer to the following code:
View Model:
public class ViewModel
{
[Required]
public int SelectedOptionID { get; set; }
}
View:
@model ViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.SelectedOptionID,
ViewBag.age as SelectList,
"Select an option")
@Html.ValidationMessageFor(Model => Model.SelectedOptionID)
}
Hope this can be helpful to you.
Sherwin Zhao
Best Regards
Thursday, March 12, 2015 5:17 AM
for dropdown validation refer this link:
http://stackoverflow.com/questions/19299459/validation-for-dropdown-list-in-mvc
Thursday, March 12, 2015 6:52 AM
Hi
Please visit this page for your solution..
Hope this will help you. Mark as answer if help it.
Thanks