Most of the questions asked regarding this are just to append a plain dropdown Html. But I was trying to dynamically adds (append) the Html.DropDownListFor helper as I need to get the list of selection from the server. The objective for this code is to submit list of Judge.JudgeBoothMark to the controller. Here is my DropDownListFor Html helper:
<div id="BoothList">
@Html.LabelFor(b => b.Booths)
@Html.DropDownListFor(m => m.Judge.JudgeBoothMark[0].BoothId, new SelectList(Model.Booths, "Id", "BoothId"), "--Select Booth--", new { @class = "form-control" })
@Html.ValidationMessageFor(b => b.Judge.JudgeBoothMark)
</div>
I used this button to add the dropdownlistfor:
<button type="button" id="addBooth">Add Booth</button>
I want to add this kind of dropdownlistfor Html helper through javascript dynamically as the number 0 from m.Judge.JudgeBoothMark[0] count will add up as I click on the button. Here is my Javascript code:
@section scripts{
<script>
$(document).ready(function () {
var count = 0;
$("#addBooth").click(function() {
count++;
@{
string dropdown = Html.DropDownListFor(m => m.Judge.JudgeBoothMark[1].BoothId,
new SelectList(Model.Booths, "Id", "BoothId"),
"--Select Booth--",
new {@class = "form-control"}).ToString();
}
var newBooth = '<br/>@Html.Raw(Ajax.JavaScriptStringEncode(dropdown))';
$("#BoothList").append(newBooth);
});
});
</script> }
Notice that the dropdownlistfor that I am using here has index 1. I can run this code fine, but the index number will be only 1, unchanged. The data that will be submitted/saved to my controller is the first and second added dropdownlist [0,1].
I cannot increase the number as I don't know how to do it. I've tried so many ways (eg; tried using the count variable, but cannot find proper way), but cannot seems to solve this problem.
Is there any way to resolve this? or is there any better way to approach my objective here?
Thanks in advance.