How to create dynamic dropdown boxes that grows in ASP.NET EF?Create dynamic forms that grow at run timeHow do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?How do you create a dropdownlist from an enum in ASP.NET MVC?How do you handle multiple submit buttons in ASP.NET MVC Framework?How to render an ASP.NET MVC view as a string?How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?Pass SelectList “SelectedValue” to Controller Action MethodHow to secure an ASP.NET Web APIasp.net mvc - How to create multiple DropDownLists using JavascriptHow to create a checkbox list?Fetching and Adding Checkbox dynamically on selection of Dropdown boxes

What does Sartre mean by "pédéraste" - pederast or homosexual?

Is there a concept of "peer review" in Rabbinical Judaism?

Number of list elements less than a given integer

Designing a time thief proof safe

Why, even after his imprisonment, people keep calling Hannibal Lecter "Doctor"?

speckled vs. spotted

End a command question

Why weren't the Death Star plans transmitted electronically?

My manager quit. Should I agree to defer wage increase to accommodate budget concerns?

Why does the leading tone (G#) go to E rather than A in this example?

How can this Stack Exchange site have an animated favicon?

How should I answer custom and border protection questions if I'm a returning citizen that hasn't been in the country for almost a decade?

Received a package but didn't order it

Why did UK NHS pay for homeopathic treatments?

How to justify getting additional team member when the current team is doing well?

Iterating over &Vec<T> and Vec<&T>

We are on WHV, my boyfriend was in a small collision, we are leaving in 2 weeks what happens if we don’t pay the damages?

Flowers sent by the birds

Clear text passwords in Unix

Diminutive -ula

Why is a road bike faster than a city bike with the same effort? How much faster it can be?

Why does (inf + 0j)*1 evaluate to inf + nanj?

Can I enter the UK without my husband if we said we'd travel together in our visa application?

Why is my abdomen much cooler than the rest of my body after a ride?



How to create dynamic dropdown boxes that grows in ASP.NET EF?


Create dynamic forms that grow at run timeHow do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?How do you create a dropdownlist from an enum in ASP.NET MVC?How do you handle multiple submit buttons in ASP.NET MVC Framework?How to render an ASP.NET MVC view as a string?How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?Pass SelectList “SelectedValue” to Controller Action MethodHow to secure an ASP.NET Web APIasp.net mvc - How to create multiple DropDownLists using JavascriptHow to create a checkbox list?Fetching and Adding Checkbox dynamically on selection of Dropdown boxes






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm trying to implement dropboxes that can appear prefilled, and can grow dynamically when you press a button. I started with a basic dropdown box implementation that doesn't grow dynamically. This is my controller+DTO code snippet:



public class TaskDTO

public string TaskTemplateName get; set;


public IActionResult Create()

ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");
return View();


public async Task<IActionResult> Create([Bind("Id,TaskTemplateName")] TaskDTO task)

if (ModelState.IsValid)

//Do some stuff

ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name", task.TaskTemplateName);
return View(task);



This is my create.cshtml razor code:



<h2>Create</h2>

<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="TaskTemplateName" class="control-label"></label>
` `<select asp-for="TaskTemplateName" class="form-control" asp-items="ViewBag.TaskTemplateId"></select>
</div>


Then I looked around and found this link that shows how to create dynamic forms that can grow. I tried to combine that idea with dropdown boxes. Based on that tutorial, here's my new DTO+controller code:



public class TaskTemplateDTO

public string TaskTemplateName get; set;


public class TaskDTO

public List<TaskTemplateDTO> TaskTemplateNames get; set;



public IActionResult Create()

var vm = new TaskDTO() ;
ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");
return View(vm);


public async Task<IActionResult> Create([Bind("Id,TaskName,TaskTemplateNames,ParentTasks,IsBasicTask,EstimatedTime,RequiredResources")] TaskDTO task)

if (ModelState.IsValid)

//Do some stuff


ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name", task.TaskTemplateNames);
return View(task);



here's my extra EditorTemplates razor, TaskTemplateDTO.cshtml:



@model Namespace.TaskTemplateDTO

<select asp-for="TaskTemplateName" class="TaskTemplate" asp-items="ViewBag.TaskTemplateId"></select>


This is my create.cshtml razor code:



<h2>Create</h2>

<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<table class="table table-bordered" id="TaskTemplateTable">
<tr>
<th>Task Templates</th>
<th><button type="button" name="add" id="btn_AddTaskTemplate" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
@Html.EditorFor(f => f.TaskTemplateNames)
</tr>
</table>
</div>
</form>
</div>
</div>



@section Scripts
@await Html.RenderPartialAsync("_ValidationScriptsPartial");

<script>

$("#btn_AddTaskTemplate").click(function ()
var i = $(".TaskTemplate").length;
var html = '';
html += '<tr>';
html += '<td><select type="text" name="TaskTemplateNames[' + i + '].TaskTemplateName" class="TaskTemplate" /></td>';
html += '<td></td></tr>';
);

$('#TaskTemplateTable').append(html);
</script>



The code above adds the new dropdowns on click, but the dropdowns aren't prefilled with data, what have I done wrong?










share|improve this question


























  • Are you adding any <option> inside the new <select> elements that get added?

    – Saharsh
    Mar 28 at 19:10











  • No, am I supposed to? I didn't know I had to

    – Mantracker
    Mar 28 at 19:47











  • I thought that <select asp-for="TaskTemplateName" class="TaskTemplate" asp-items="ViewBag.TaskTemplateId"></select> would automatically pick the items to be added for me

    – Mantracker
    Mar 28 at 19:48











  • You would need to specify the options you want in your <select> because you're building the html string fresh for each click. Which options are you trying to add to the select?

    – Saharsh
    Mar 28 at 20:01












  • I'm trying to add the stored models in ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");. So I want all the TaskTemplates from _context.TaskTemplates. Each item in the TaskTemplates list should be an option in the select

    – Mantracker
    Mar 28 at 20:14

















0















I'm trying to implement dropboxes that can appear prefilled, and can grow dynamically when you press a button. I started with a basic dropdown box implementation that doesn't grow dynamically. This is my controller+DTO code snippet:



public class TaskDTO

public string TaskTemplateName get; set;


public IActionResult Create()

ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");
return View();


public async Task<IActionResult> Create([Bind("Id,TaskTemplateName")] TaskDTO task)

if (ModelState.IsValid)

//Do some stuff

ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name", task.TaskTemplateName);
return View(task);



This is my create.cshtml razor code:



<h2>Create</h2>

<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="TaskTemplateName" class="control-label"></label>
` `<select asp-for="TaskTemplateName" class="form-control" asp-items="ViewBag.TaskTemplateId"></select>
</div>


Then I looked around and found this link that shows how to create dynamic forms that can grow. I tried to combine that idea with dropdown boxes. Based on that tutorial, here's my new DTO+controller code:



public class TaskTemplateDTO

public string TaskTemplateName get; set;


public class TaskDTO

public List<TaskTemplateDTO> TaskTemplateNames get; set;



public IActionResult Create()

var vm = new TaskDTO() ;
ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");
return View(vm);


public async Task<IActionResult> Create([Bind("Id,TaskName,TaskTemplateNames,ParentTasks,IsBasicTask,EstimatedTime,RequiredResources")] TaskDTO task)

if (ModelState.IsValid)

//Do some stuff


ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name", task.TaskTemplateNames);
return View(task);



here's my extra EditorTemplates razor, TaskTemplateDTO.cshtml:



@model Namespace.TaskTemplateDTO

<select asp-for="TaskTemplateName" class="TaskTemplate" asp-items="ViewBag.TaskTemplateId"></select>


This is my create.cshtml razor code:



<h2>Create</h2>

<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<table class="table table-bordered" id="TaskTemplateTable">
<tr>
<th>Task Templates</th>
<th><button type="button" name="add" id="btn_AddTaskTemplate" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
@Html.EditorFor(f => f.TaskTemplateNames)
</tr>
</table>
</div>
</form>
</div>
</div>



@section Scripts
@await Html.RenderPartialAsync("_ValidationScriptsPartial");

<script>

$("#btn_AddTaskTemplate").click(function ()
var i = $(".TaskTemplate").length;
var html = '';
html += '<tr>';
html += '<td><select type="text" name="TaskTemplateNames[' + i + '].TaskTemplateName" class="TaskTemplate" /></td>';
html += '<td></td></tr>';
);

$('#TaskTemplateTable').append(html);
</script>



The code above adds the new dropdowns on click, but the dropdowns aren't prefilled with data, what have I done wrong?










share|improve this question


























  • Are you adding any <option> inside the new <select> elements that get added?

    – Saharsh
    Mar 28 at 19:10











  • No, am I supposed to? I didn't know I had to

    – Mantracker
    Mar 28 at 19:47











  • I thought that <select asp-for="TaskTemplateName" class="TaskTemplate" asp-items="ViewBag.TaskTemplateId"></select> would automatically pick the items to be added for me

    – Mantracker
    Mar 28 at 19:48











  • You would need to specify the options you want in your <select> because you're building the html string fresh for each click. Which options are you trying to add to the select?

    – Saharsh
    Mar 28 at 20:01












  • I'm trying to add the stored models in ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");. So I want all the TaskTemplates from _context.TaskTemplates. Each item in the TaskTemplates list should be an option in the select

    – Mantracker
    Mar 28 at 20:14













0












0








0


1






I'm trying to implement dropboxes that can appear prefilled, and can grow dynamically when you press a button. I started with a basic dropdown box implementation that doesn't grow dynamically. This is my controller+DTO code snippet:



public class TaskDTO

public string TaskTemplateName get; set;


public IActionResult Create()

ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");
return View();


public async Task<IActionResult> Create([Bind("Id,TaskTemplateName")] TaskDTO task)

if (ModelState.IsValid)

//Do some stuff

ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name", task.TaskTemplateName);
return View(task);



This is my create.cshtml razor code:



<h2>Create</h2>

<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="TaskTemplateName" class="control-label"></label>
` `<select asp-for="TaskTemplateName" class="form-control" asp-items="ViewBag.TaskTemplateId"></select>
</div>


Then I looked around and found this link that shows how to create dynamic forms that can grow. I tried to combine that idea with dropdown boxes. Based on that tutorial, here's my new DTO+controller code:



public class TaskTemplateDTO

public string TaskTemplateName get; set;


public class TaskDTO

public List<TaskTemplateDTO> TaskTemplateNames get; set;



public IActionResult Create()

var vm = new TaskDTO() ;
ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");
return View(vm);


public async Task<IActionResult> Create([Bind("Id,TaskName,TaskTemplateNames,ParentTasks,IsBasicTask,EstimatedTime,RequiredResources")] TaskDTO task)

if (ModelState.IsValid)

//Do some stuff


ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name", task.TaskTemplateNames);
return View(task);



here's my extra EditorTemplates razor, TaskTemplateDTO.cshtml:



@model Namespace.TaskTemplateDTO

<select asp-for="TaskTemplateName" class="TaskTemplate" asp-items="ViewBag.TaskTemplateId"></select>


This is my create.cshtml razor code:



<h2>Create</h2>

<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<table class="table table-bordered" id="TaskTemplateTable">
<tr>
<th>Task Templates</th>
<th><button type="button" name="add" id="btn_AddTaskTemplate" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
@Html.EditorFor(f => f.TaskTemplateNames)
</tr>
</table>
</div>
</form>
</div>
</div>



@section Scripts
@await Html.RenderPartialAsync("_ValidationScriptsPartial");

<script>

$("#btn_AddTaskTemplate").click(function ()
var i = $(".TaskTemplate").length;
var html = '';
html += '<tr>';
html += '<td><select type="text" name="TaskTemplateNames[' + i + '].TaskTemplateName" class="TaskTemplate" /></td>';
html += '<td></td></tr>';
);

$('#TaskTemplateTable').append(html);
</script>



The code above adds the new dropdowns on click, but the dropdowns aren't prefilled with data, what have I done wrong?










share|improve this question
















I'm trying to implement dropboxes that can appear prefilled, and can grow dynamically when you press a button. I started with a basic dropdown box implementation that doesn't grow dynamically. This is my controller+DTO code snippet:



public class TaskDTO

public string TaskTemplateName get; set;


public IActionResult Create()

ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");
return View();


public async Task<IActionResult> Create([Bind("Id,TaskTemplateName")] TaskDTO task)

if (ModelState.IsValid)

//Do some stuff

ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name", task.TaskTemplateName);
return View(task);



This is my create.cshtml razor code:



<h2>Create</h2>

<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="TaskTemplateName" class="control-label"></label>
` `<select asp-for="TaskTemplateName" class="form-control" asp-items="ViewBag.TaskTemplateId"></select>
</div>


Then I looked around and found this link that shows how to create dynamic forms that can grow. I tried to combine that idea with dropdown boxes. Based on that tutorial, here's my new DTO+controller code:



public class TaskTemplateDTO

public string TaskTemplateName get; set;


public class TaskDTO

public List<TaskTemplateDTO> TaskTemplateNames get; set;



public IActionResult Create()

var vm = new TaskDTO() ;
ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");
return View(vm);


public async Task<IActionResult> Create([Bind("Id,TaskName,TaskTemplateNames,ParentTasks,IsBasicTask,EstimatedTime,RequiredResources")] TaskDTO task)

if (ModelState.IsValid)

//Do some stuff


ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name", task.TaskTemplateNames);
return View(task);



here's my extra EditorTemplates razor, TaskTemplateDTO.cshtml:



@model Namespace.TaskTemplateDTO

<select asp-for="TaskTemplateName" class="TaskTemplate" asp-items="ViewBag.TaskTemplateId"></select>


This is my create.cshtml razor code:



<h2>Create</h2>

<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<table class="table table-bordered" id="TaskTemplateTable">
<tr>
<th>Task Templates</th>
<th><button type="button" name="add" id="btn_AddTaskTemplate" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
@Html.EditorFor(f => f.TaskTemplateNames)
</tr>
</table>
</div>
</form>
</div>
</div>



@section Scripts
@await Html.RenderPartialAsync("_ValidationScriptsPartial");

<script>

$("#btn_AddTaskTemplate").click(function ()
var i = $(".TaskTemplate").length;
var html = '';
html += '<tr>';
html += '<td><select type="text" name="TaskTemplateNames[' + i + '].TaskTemplateName" class="TaskTemplate" /></td>';
html += '<td></td></tr>';
);

$('#TaskTemplateTable').append(html);
</script>



The code above adds the new dropdowns on click, but the dropdowns aren't prefilled with data, what have I done wrong?







c# asp.net-mvc






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 18:45







Mantracker

















asked Mar 28 at 18:39









MantrackerMantracker

3104 silver badges16 bronze badges




3104 silver badges16 bronze badges















  • Are you adding any <option> inside the new <select> elements that get added?

    – Saharsh
    Mar 28 at 19:10











  • No, am I supposed to? I didn't know I had to

    – Mantracker
    Mar 28 at 19:47











  • I thought that <select asp-for="TaskTemplateName" class="TaskTemplate" asp-items="ViewBag.TaskTemplateId"></select> would automatically pick the items to be added for me

    – Mantracker
    Mar 28 at 19:48











  • You would need to specify the options you want in your <select> because you're building the html string fresh for each click. Which options are you trying to add to the select?

    – Saharsh
    Mar 28 at 20:01












  • I'm trying to add the stored models in ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");. So I want all the TaskTemplates from _context.TaskTemplates. Each item in the TaskTemplates list should be an option in the select

    – Mantracker
    Mar 28 at 20:14

















  • Are you adding any <option> inside the new <select> elements that get added?

    – Saharsh
    Mar 28 at 19:10











  • No, am I supposed to? I didn't know I had to

    – Mantracker
    Mar 28 at 19:47











  • I thought that <select asp-for="TaskTemplateName" class="TaskTemplate" asp-items="ViewBag.TaskTemplateId"></select> would automatically pick the items to be added for me

    – Mantracker
    Mar 28 at 19:48











  • You would need to specify the options you want in your <select> because you're building the html string fresh for each click. Which options are you trying to add to the select?

    – Saharsh
    Mar 28 at 20:01












  • I'm trying to add the stored models in ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");. So I want all the TaskTemplates from _context.TaskTemplates. Each item in the TaskTemplates list should be an option in the select

    – Mantracker
    Mar 28 at 20:14
















Are you adding any <option> inside the new <select> elements that get added?

– Saharsh
Mar 28 at 19:10





Are you adding any <option> inside the new <select> elements that get added?

– Saharsh
Mar 28 at 19:10













No, am I supposed to? I didn't know I had to

– Mantracker
Mar 28 at 19:47





No, am I supposed to? I didn't know I had to

– Mantracker
Mar 28 at 19:47













I thought that <select asp-for="TaskTemplateName" class="TaskTemplate" asp-items="ViewBag.TaskTemplateId"></select> would automatically pick the items to be added for me

– Mantracker
Mar 28 at 19:48





I thought that <select asp-for="TaskTemplateName" class="TaskTemplate" asp-items="ViewBag.TaskTemplateId"></select> would automatically pick the items to be added for me

– Mantracker
Mar 28 at 19:48













You would need to specify the options you want in your <select> because you're building the html string fresh for each click. Which options are you trying to add to the select?

– Saharsh
Mar 28 at 20:01






You would need to specify the options you want in your <select> because you're building the html string fresh for each click. Which options are you trying to add to the select?

– Saharsh
Mar 28 at 20:01














I'm trying to add the stored models in ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");. So I want all the TaskTemplates from _context.TaskTemplates. Each item in the TaskTemplates list should be an option in the select

– Mantracker
Mar 28 at 20:14





I'm trying to add the stored models in ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");. So I want all the TaskTemplates from _context.TaskTemplates. Each item in the TaskTemplates list should be an option in the select

– Mantracker
Mar 28 at 20:14












1 Answer
1






active

oldest

votes


















0
















You will need to have the select options that you want in the new controls to be available to your javascript method. There are a few ways to do it, the most straightforward would be to hide it in your html page in a hidden select control.



Your CSHTML:



<h2>Create</h2>

//Added the hidden HTML control here
@Html.DropDownList("hidden-select",
new SelectList((IEnumerable) ViewData["TaskTemplateId"]),
null, new Dictionary<string, object>

"id", "task-template-names" ,
"style", "display: none"
)
<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
////other things you were doing


This will render in your html as a prepopulated hidden template from which you can build new dropdowns with options on button click.



 $("#btn_AddTaskTemplate").click(function () 
var i = $(".TaskTemplate").length;
var html = '';
html += '<tr>';
html += '<td><select type="text" name="TaskTemplateNames[' + i + '].TaskTemplateName" class="TaskTemplate">';
html += document.querySelector("#task-template-names").innerHTML;
html += '</select></td>';
html += '<td></td></tr>';
);


I wasn't able to test this code because the setup is beyond my scope here, so you might need to tweak it a little bit. If you encounter any difficult errors, let me know.






share|improve this answer



























  • Hi @Saharsh, I don't have an original prepopulated select. The select statement is dynamically added, whenever a button is pressed, so where should I get this "ID_OF_YOUR_ORIGINAL_PREPOPULATED_SELECT"?

    – Mantracker
    Mar 28 at 21:34











  • update the answer

    – Saharsh
    Mar 29 at 3:40













Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);














draft saved

draft discarded
















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55404744%2fhow-to-create-dynamic-dropdown-boxes-that-grows-in-asp-net-ef%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0
















You will need to have the select options that you want in the new controls to be available to your javascript method. There are a few ways to do it, the most straightforward would be to hide it in your html page in a hidden select control.



Your CSHTML:



<h2>Create</h2>

//Added the hidden HTML control here
@Html.DropDownList("hidden-select",
new SelectList((IEnumerable) ViewData["TaskTemplateId"]),
null, new Dictionary<string, object>

"id", "task-template-names" ,
"style", "display: none"
)
<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
////other things you were doing


This will render in your html as a prepopulated hidden template from which you can build new dropdowns with options on button click.



 $("#btn_AddTaskTemplate").click(function () 
var i = $(".TaskTemplate").length;
var html = '';
html += '<tr>';
html += '<td><select type="text" name="TaskTemplateNames[' + i + '].TaskTemplateName" class="TaskTemplate">';
html += document.querySelector("#task-template-names").innerHTML;
html += '</select></td>';
html += '<td></td></tr>';
);


I wasn't able to test this code because the setup is beyond my scope here, so you might need to tweak it a little bit. If you encounter any difficult errors, let me know.






share|improve this answer



























  • Hi @Saharsh, I don't have an original prepopulated select. The select statement is dynamically added, whenever a button is pressed, so where should I get this "ID_OF_YOUR_ORIGINAL_PREPOPULATED_SELECT"?

    – Mantracker
    Mar 28 at 21:34











  • update the answer

    – Saharsh
    Mar 29 at 3:40















0
















You will need to have the select options that you want in the new controls to be available to your javascript method. There are a few ways to do it, the most straightforward would be to hide it in your html page in a hidden select control.



Your CSHTML:



<h2>Create</h2>

//Added the hidden HTML control here
@Html.DropDownList("hidden-select",
new SelectList((IEnumerable) ViewData["TaskTemplateId"]),
null, new Dictionary<string, object>

"id", "task-template-names" ,
"style", "display: none"
)
<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
////other things you were doing


This will render in your html as a prepopulated hidden template from which you can build new dropdowns with options on button click.



 $("#btn_AddTaskTemplate").click(function () 
var i = $(".TaskTemplate").length;
var html = '';
html += '<tr>';
html += '<td><select type="text" name="TaskTemplateNames[' + i + '].TaskTemplateName" class="TaskTemplate">';
html += document.querySelector("#task-template-names").innerHTML;
html += '</select></td>';
html += '<td></td></tr>';
);


I wasn't able to test this code because the setup is beyond my scope here, so you might need to tweak it a little bit. If you encounter any difficult errors, let me know.






share|improve this answer



























  • Hi @Saharsh, I don't have an original prepopulated select. The select statement is dynamically added, whenever a button is pressed, so where should I get this "ID_OF_YOUR_ORIGINAL_PREPOPULATED_SELECT"?

    – Mantracker
    Mar 28 at 21:34











  • update the answer

    – Saharsh
    Mar 29 at 3:40













0














0










0









You will need to have the select options that you want in the new controls to be available to your javascript method. There are a few ways to do it, the most straightforward would be to hide it in your html page in a hidden select control.



Your CSHTML:



<h2>Create</h2>

//Added the hidden HTML control here
@Html.DropDownList("hidden-select",
new SelectList((IEnumerable) ViewData["TaskTemplateId"]),
null, new Dictionary<string, object>

"id", "task-template-names" ,
"style", "display: none"
)
<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
////other things you were doing


This will render in your html as a prepopulated hidden template from which you can build new dropdowns with options on button click.



 $("#btn_AddTaskTemplate").click(function () 
var i = $(".TaskTemplate").length;
var html = '';
html += '<tr>';
html += '<td><select type="text" name="TaskTemplateNames[' + i + '].TaskTemplateName" class="TaskTemplate">';
html += document.querySelector("#task-template-names").innerHTML;
html += '</select></td>';
html += '<td></td></tr>';
);


I wasn't able to test this code because the setup is beyond my scope here, so you might need to tweak it a little bit. If you encounter any difficult errors, let me know.






share|improve this answer















You will need to have the select options that you want in the new controls to be available to your javascript method. There are a few ways to do it, the most straightforward would be to hide it in your html page in a hidden select control.



Your CSHTML:



<h2>Create</h2>

//Added the hidden HTML control here
@Html.DropDownList("hidden-select",
new SelectList((IEnumerable) ViewData["TaskTemplateId"]),
null, new Dictionary<string, object>

"id", "task-template-names" ,
"style", "display: none"
)
<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
////other things you were doing


This will render in your html as a prepopulated hidden template from which you can build new dropdowns with options on button click.



 $("#btn_AddTaskTemplate").click(function () 
var i = $(".TaskTemplate").length;
var html = '';
html += '<tr>';
html += '<td><select type="text" name="TaskTemplateNames[' + i + '].TaskTemplateName" class="TaskTemplate">';
html += document.querySelector("#task-template-names").innerHTML;
html += '</select></td>';
html += '<td></td></tr>';
);


I wasn't able to test this code because the setup is beyond my scope here, so you might need to tweak it a little bit. If you encounter any difficult errors, let me know.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 29 at 3:40

























answered Mar 28 at 21:05









SaharshSaharsh

6666 silver badges17 bronze badges




6666 silver badges17 bronze badges















  • Hi @Saharsh, I don't have an original prepopulated select. The select statement is dynamically added, whenever a button is pressed, so where should I get this "ID_OF_YOUR_ORIGINAL_PREPOPULATED_SELECT"?

    – Mantracker
    Mar 28 at 21:34











  • update the answer

    – Saharsh
    Mar 29 at 3:40

















  • Hi @Saharsh, I don't have an original prepopulated select. The select statement is dynamically added, whenever a button is pressed, so where should I get this "ID_OF_YOUR_ORIGINAL_PREPOPULATED_SELECT"?

    – Mantracker
    Mar 28 at 21:34











  • update the answer

    – Saharsh
    Mar 29 at 3:40
















Hi @Saharsh, I don't have an original prepopulated select. The select statement is dynamically added, whenever a button is pressed, so where should I get this "ID_OF_YOUR_ORIGINAL_PREPOPULATED_SELECT"?

– Mantracker
Mar 28 at 21:34





Hi @Saharsh, I don't have an original prepopulated select. The select statement is dynamically added, whenever a button is pressed, so where should I get this "ID_OF_YOUR_ORIGINAL_PREPOPULATED_SELECT"?

– Mantracker
Mar 28 at 21:34













update the answer

– Saharsh
Mar 29 at 3:40





update the answer

– Saharsh
Mar 29 at 3:40




















draft saved

draft discarded















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55404744%2fhow-to-create-dynamic-dropdown-boxes-that-grows-in-asp-net-ef%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript