1

I have a piece of code in Javascript which contains definition of a dropdownlist. I don't know how to pass parameter like name of the dropdownlist.

var x=1;
var block='<div class="col-md-3">' +
          '<div class="form-group">' +
               '<label for="Address">Adresa '+ addressOUPIndex+' de la OUP</label><br />' +
               '@Ajax.JavaScriptStringEncode(Html.DropDownList("addresses["+ (x- 1) + "].Address",EnumHelper.GetSelectList(typeof(EPURE.Common.Enums.AdresaOUP)), null, new { @class = "selectpicker Address"}).ToHtmlString())' +
                                                                         ^^^^^^^^^^^
          '</div>' +
'</div>' +

I receive follow error:

The name 'x' does not exist in the current context

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
  • `Html.DropDownList()` is razor code and its parsed on the server before its sent to the view. `x` is a javascript variable that does not exist at that point –  Apr 04 '17 at 10:43
  • Thanks for information, @StephenMuecke. How can I solve the problem ? – Mihai Alexandru-Ionut Apr 04 '17 at 10:43
  • 1
    I assume your trying to dynamically add collection items? (in which case, refer some options [here](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308)) –  Apr 04 '17 at 10:44

1 Answers1

1

Try to replace your string:

var replacedVariable = 1; // unique name inside your 'myString' for replace
var myString = '@Ajax.JavaScriptStringEncode(Html.DropDownList("addresses[replacedVariable].Address",EnumHelper.GetSelectList(typeof(EPURE.Common.Enums.AdresaOUP)), null, new { @class = "selectpicker Address"}).ToHtmlString())';
myString = myString.replace('replacedVariable', replacedVariable); // addresses[1].Address

var block='<div class="col-md-3">' +
      '<div class="form-group">' +
           '<label for="Address">Adresa '+ addressOUPIndex+' de la OUP</label><br />' +
          myString  +                                                  
      '</div>' +
'</div>'
Denis Bubnov
  • 2,619
  • 5
  • 30
  • 54