Validation of DropDownListFor is not working in MVC3?

178 Views Asked by At

Validation is Working on Other Input type text element but not working on DropDownListFor

Class Purchase Input Property Code

[Required]
public string LedgerId { get; set; }

Class View Model Code

PurchaseViewModel purchaseVM = new PurchaseViewModel
{
    // PurchaseInput=purchaseInput,
    Ledger = uw.LedgerRepository.Get().Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.LedgerName }),
};

View

<div class="column">
    <div  class="labelField">
        @Html.LabelFor(model => model.PurchaseInput.LedgerId, "Party")
    </div>   
    <div class="ItemField">
        @Html.DropDownListFor(model => model.PurchaseInput.LedgerId, new SelectList(Model.Ledger, "Value", "Text"))
        @Html.ValidationMessageFor(model => model.PurchaseInput.LedgerId)
    </div>
</div>
3

There are 3 best solutions below

0
On

Yes, there are problems with validation of DropDownListFor. look at this link. They get validation data manually from metadata - http://forums.asp.net/t/1649193.aspx

0
On

On the face of it, it seems that you do not have an empty item in your select list. The validation will only trigger if the user selects a dropdown item with string length of zero. If you examine the Html source can you see the validation attributes on the dropdown ( depending on whether you are using unobtrusive validation or not)?

0
On

Although this is a workaround, at least it fires some sort of validation. Try:

@Html.DropDownListFor(model => model.PurchaseInput.LedgerId, new SelectList(Model.Ledger, "Value", "Text"), new { @class = "required" })