Pass html code as a string in javaScript in c# mvc

In HTML page, I want to add a dynamic dropdown list after a button click. So on onClick I am trying to add a dropdown list to the HTML block, but to convert the dropdown list as a string I am facing a problem, so can anyone help on this. Below I have provided the code for dropdown but I am facing a problem, to make that as a string before passing it to HTML.

 var dropDownTime='<div class="input-group">'+'@Html.DropDownList("Data", new List<SelectListItem>{
                                                                                new SelectListItem{ Text="Custom Range", Value ="Custom Range" },
                                                                                new SelectListItem{ Text="Last 30 minutes", Value ="Last 30 minutes" },
                                                                                new SelectListItem{ Text="Last 1 hour", Value ="Last 1 hour" }                                                                                    
            }, "Select Data", new { @ng_model = "fileterparameter", @id = "Data", @class = "form-control" })'+
            '<span class="input-group-btn">'+
                '<button class="btn btn-primary" type="button" id="filterlink"><i class="glyphicon glyphicon-filter"></i></button>'+
            '</span>'+
        '</div>';

1 answer

  • answered 2018-05-16 06:52 Codex

    I think its not working because you have used the HTML.Dropdownlist inside quotes. Its an object we need to build to get the values in the dropdown. Please try the following code.

    var dropDownTime='<div class="input-group">'+@Html.DropDownList("Data", new List<SelectListItem>{
                                                                                new SelectListItem{ Text="Custom Range", Value ="Custom Range" },
                                                                                new SelectListItem{ Text="Last 30 minutes", Value ="Last 30 minutes" },
                                                                                new SelectListItem{ Text="Last 1 hour", Value ="Last 1 hour" }                                                                                    
            }, "Select Data", new { @ng_model = "fileterparameter", @id = "Data", @class = "form-control" })+
            '<span class="input-group-btn">'+
                '<button class="btn btn-primary" type="button" id="filterlink"><i class="glyphicon glyphicon-filter"></i></button>'+
            '</span>'+
        '</div>';