Showing posts with label .Net MVC. Show all posts
Showing posts with label .Net MVC. Show all posts

Monday, 22 August 2022

Use of .map in jQuery to get selected checkboxes values:

HTML:
<input type="checkbox" class="chkitem" value="1"/>
<input type="checkbox" class="chkitem" value="2"/>
<input type="checkbox" class="chkitem" value="3"/>

jQuery:
var ids = $(".chkitem:checked").map(function () {
                        return $(this).val();
                    }).get();

Simple C# code to Validating email address

 public static bool ValidateEmail(string email)
 {
      string regex = @"^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+\.)+[a-z]{2,5}$";
       return Regex.IsMatch(email, regex);
  }

Formatting phonenumber by removing all alphabets and characters except "+" and numbers in c#.

        public static string FormatPhoneNumber(string phoneNumber)
        {
            phoneNumber = Regex.Replace(phoneNumber, "[^0-9+]", "");
            if (phoneNumber == "+")
            {
                phoneNumber = string.Empty;
            }
            return phoneNumber;
        } 

Thursday, 1 August 2019

.Net MVC helper to generate Dropdown from Enum

.Net MVC provides helper method to generate a dropdown using Enum. Suppose you have a Roles enum and you want to generate a dropdown for roles.

//Roles Enum
public enum RolesEnum
{
    Admin = 1,
    Manager = 2,
    User = 3
}

//Model class
public class CreateUser
{
    public RolesEnum? Roles {get; set;}
}

// MVC helper
@Html.EnumDropDownListFor(m => m.Roles, "Select Role", new { @class = "form-control", data_val = true, required = "required" })