Critical Developers

Programmers Knowledge Base

Bind Static DropDownListFor in MVC

Get and Set DropdownList in MVC

Binding the dropdown using database is easy in MVC what if the Dropdown is static (i.e. you have to hard code the values in dropdown). The logic is to use Request.Form while passing data from view to conttroller and while setting the values use List<>

In View design your dropdownlist will be as shown below :-

 @{
List<string> loProductTypes = new List<string>(Convert.ToString("Type1,Type2,Type3,Type4").Split(','));
IEnumerable<SelectListItem> loProductTypeSelectList =
loProductTypes.Select(x =>new SelectListItem() { Text = x.ToString(), Value = x.ToString() });
}

@Html.DropDownListFor(model => model.ProductTypes,loProductTypeSelectList)


In Controller while inserting/updating use below code :-

ModelObjectName.ProductTypes = Convert.ToString(Request.Form["stProductTypes"]);

Check Future Date Validation in MVC

Check Future Date Validation in MVC
Hi, Today I come up with a very common issue (i.e.: Check if date is Future Date) which was very easy in ASP.Net web form but in MVC it is a bit tricky.
The trick is nothing but we have to write our own validator. This process can be useful in validation of Birthdate and etc. So lets start adding a custom validator for same.

Add a usual js function to check if it is future date or not :-

jQuery.validator.addMethod("isfuturedate", function (value, element, params) {
    if (value != "__/__/____" && value != "") {
        var mm = value.substr(0, 2);
        var dd = value.substr(2, 2);
        var yyyy = value.substr(4, 4);
        var fdtDate = mm + "/" + dd + "/" + yyyy;
        fdtDate = Date.parse(fdtDate);      // console.log(fdtDate);       
        var ldtCurrentDate = new Date();
        if (fdtDate > ldtCurrentDate) {
            return false;
        }
    }
    return true;
});

Register the above method in jquery.validators adapter :-

jQuery.validator.unobtrusive.adapters.add("isfuturedate", function (options) {
    if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "TEXT") {
        options.rules["isfuturedate"] = true;
        if (options.message) {
            options.messages["isfuturedate"] = options.message;
        }
    }
});

Write same logic in your model for server side validation :-

    public class NoFutureDateAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            DateTime loDate = Convert.ToDateTime(value);
            if (loDate > DateTime.Now)
                return false;
            return true;    // default true
        }
        // Implement IClientValidatable for client side Validation
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "isfuturedate", ErrorMessage = this.ErrorMessage } };
        }
    }

Apply Data Annotation Attributes as below :-

        [NoFutureDate(ErrorMessage = "Date cannot be greater than todays date.")]
        [DisplayName("Birth Date")]
        [DataType(DataType.Date), DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
        public object stBirthdate { get; set; }