Thursday 31 January 2013

Dynamically adding Controls in the Asp.Net MVC3 / MVC4.

This post is so simple that you can easily understand how to add controls to your view dynamically and delete controls dynamically, i.e. here the controls are created dynamically and are deleted dynamically.

The Above thing can be achieved  in 3 steps:

1. Creating the View.
2. Handling the Click event and creating/deleting the Dynamic Control.
3. Pulling the data from the View to the Controller.


1.Creating the View:

First of all you need to create a view for the Dynamic control Adding.

For Example:
<div>
    <label class="smallFontForAppSelector">Name</label>
    &nbsp;&nbsp;
    <label class="smallFontForAppSelector">
        Degree of Similarity
    </label>
    <label class="smallFontForAppSelector">
        URL/Location
    </label>
    <label class="smallFontForAppSelector">
        Info
    </label>
    <label class="smallFontForAppSelector">
        GUID
    </label>
</div>
<div id='AppSelectorGroup'>
    <div id="AppSelectorBox_1" style="display: block; float: left;">
        <div class="editor-label">@Html.Label("Best Alternative App:")</div>
        <div class="editor-field">
            @Html.TextBox("Name", null, new { id = "textboxName1" })
            &nbsp;&nbsp;
            @Html.DropDownList("Degree", Util.GetSelectListForDegreeOfSimilarity(typeof(DegreeOfSimilarity)),"--Select--", new { id = "ddlDegree1" })
            &nbsp;&nbsp;
             @Html.TextBox("Location", null, new { id = "textboxLocation1" })
            &nbsp;&nbsp;
             @Html.TextBox("Info", null, new { id = "textboxInfo1" })
            &nbsp;&nbsp;
             @Html.TextBox("GUID", null, new { id = "textboxGUID1", @class="deleteAppselector" })
        </div>
    </div>

    <a href="#Add" class="addURL addURLBlack" id="addAppSelector">+</a> <a href="#Delete" class="addURL addURLRed" id="removeAppSelector">-</a>
    <div class="clear-fix"></div>
</div>

Css:

#AppSelectorGroup input {
    width: 140px!important;
}

.smallFontForAppSelector {
    display: block;
    float: left;
    font-size: 12px;
    position: relative;
    text-align: center;
    top: 10px;
    width: 165px;
}

.divinline {
    display: inline;
    float: left;
    width: 1100px;
}



.addURL {
    background-color: #FFF;
    border: 1px solid Gray;
    font-weight: bold;
    cursor: pointer;
    display: block;
    font-size: 15px;
    height: 23px;
    margin-left: 13px;
    margin-top: 10px;
    text-align: center;
    width: 25px;
    float: left;
}

.addURLRed {
    color: red!important;
}

.addURLBlack {
    color: #000 !important;
}

In the Enum Class:
public enum DegreeOfSimilarity
    {
        [Description("Identical")]
        Identical,
        [Description("Knock off")]
        Knockoff,
        [Description("3rd party client")]
        ThirdPartyClient,
        [Description("Functionality similar")]
        FunctionalitySimilar,
        [Description("Competitor's app")]
        CompetitorsApp,
        [Description("Mobile site substitute")]
        Substitute
    }

MY Util Class:

  public static SelectList GetSelectListForDegreeOfSimilarity(Type enumType)
        {
            List<AppDegreeOfSimilarity> appDegreeOfSimilarity = new List<AppDegreeOfSimilarity>();
            var categories = new List<string>(Enum.GetNames(enumType));

            foreach (var item in categories)
            {
                string description = ModelUtil.GetEnumDescription((DegreeOfSimilarity)Enum.Parse(typeof(DegreeOfSimilarity), item));
                appDegreeOfSimilarity.Add(new AppDegreeOfSimilarity() { Name = description, Value = item });     //LocalizationResourceProvider.GetLocalizedString("lbl" + item));
            }
            return new SelectList(appDegreeOfSimilarity, "Value", "Name");
        }


Get the Enum Description:

  public static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(
                typeof(DescriptionAttribute),
                false);

            if (attributes != null &&
                attributes.Length > 0)
                return attributes[0].Description;
            else
                return value.ToString();
        }
Jquery for handling the Click Event and Creating the Dynamic Controls:
   //----------Begin: For Creating App Selector Groups---------------//
        var deleteAppSelectror = $(".deleteAppselector").length;




/* For Adding the Control */
 $("#addAppSelector").click(function () {
     if (deleteAppSelectror == 10) {
                $("#addAppSelector").hide();
                $("#removeAppSelector").show();
                //alert("Only 10 URLs are allowed");
                return false;
            }
            else {
                $("#addAppSelector").show();
                $("#removeAppSelector").show();
            }
     deleteAppSelectror++;
     var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'AppSelectorBox__' + deleteAppSelectror);
              

            newTextBoxDiv.append('<div class="editor-label"><label>Best Alternative App: </label></div>' +
                '<div class="editor-field"><input type="text" name="Name" id="textboxName' + deleteAppSelectror + '" value="" />' + '&nbsp;&nbsp;&nbsp; <select name="Degree" id="ddlDegree' + deleteAppSelectror + '" class="valid"><option value="Identical">Identical</option> <option value="Knockoff">Knock off</option> <option value="ThirdPartyClient">3rd party client</option> <option value="FunctionalitySimilar">Functionality similar</option> <option value="CompetitorsApp">Competitors app</option> <option value="Substitute">Mobile site substitute</option> </select>' +
                '&nbsp;&nbsp;<input type="text" name="Location" id="textboxLocation' + deleteAppSelectror + '" style="margin-left:8px;" value="" />' +
              '&nbsp;&nbsp;<input type="text" name="Info" id="textboxGUID' + deleteAppSelectror + '" style="margin-left:8px;" value="" />' +
                  '&nbsp;&nbsp;<input type="text" name="GUID" class="deleteAppselector" id="textboxInfo' + deleteAppSelectror + '" style="margin-left:8px;" value="" />' +
                '</div><div class="clear-fix"></div>');

            newTextBoxDiv.appendTo("#AppSelectorGroup");


            if (deleteAppSelectror == 10) {
                 $("#addAppSelector").hide();
                 $("#removeAppSelector").show();

                 return false;
             }
             return true;
         });

/* For Removing the Control */   
     $("#removeAppSelector").click(function () {
            if (deleteAppSelectror == 1) {
                $("#removeAppSelector").hide();
                $("#addAppSelector").show();
                return false;
            }
            else {
                $("#removeAppSelector").show();
                $("#addAppSelector").show();
            }

            $('.deleteAppselector').last().parent().parent().remove();
            deleteAppSelectror--;
            if (deleteAppSelectror == 1) {
                $("#removeAppSelector").hide();
                $("#addAppSelector").show();
                return false;
            }
            return true;
        });

        //----------End: For Creating App Selector Groups---------------//



Controller: Action Method to Get the Data from View and to do processing
         [HttpPost]
        public ActionResult CreateAppSelector(AppSelectorRecordViewModel model, List<string> name, List<string> degree, List<string> location, List<string> info,List<string> guid)
        {
            GetAllBestAltApp(model, name, degree, location, info, guid);
            return CreateAppSelector(model);
        }


 private void GetAllBestAltApp(AppSelectorRecordViewModel model, List<string> name, List<string> degree, List<string> location, List<string> info, List<string> guid)
        {
            int count = 0;
            List<BestAlternatives> bestAltApps = new List<BestAlternatives>();
            if (name != null)
            {
                foreach (var n in name)
                {
                    if (n != string.Empty)
                    {
                        BestAlternatives bestAltApp = new BestAlternatives { Name = name[count], DegreeOfSimilarity = degree[count], Location = location[count], Info = info[count], GUID = guid[count] };
                        count++;
                        bestAltApps.Add(bestAltApp);
                    }
                }

                if (bestAltApps.Any())
                {

                    model.AppSelector.BestAlternatives = ModelUtil.SerializeObject(bestAltApps);
                }
                else
                {
                    model.AppSelector.BestAlternatives = null;
                }
            }
            else
                model.AppSelector.BestAlternatives = null;
        }


Result: 





No comments:

Post a Comment