Ufuk Doğan
Ufuk Doğan

Reputation: 47

Javascript Dynamically Add Option Value

I created a select tagged element but I want to fill this with my model's data, but I can't do it.

This is my code:

<select id=senderAdress" + element + " class=senderAdressText2> </select>

var element = 0;
while(element!==3){
  var obj = document.getElementById("senderAdress"+element);
  var opt = document.createElement("option");
  opt.value=element+1;
  opt.text = "@Html.DisplayFor(model=>model.Address[element].AddressName)";
  element++;
}

This is not working because in the opt.text part as you can see I want to reach my model's addressName where my Address[element]. At the top of my while I created a variable "element" and I assigned it as 0.

The problem is when I wrote Address[element] I got an error which tells me

The name element does not exist in current context,

but as you can see I assigned it at top and if it is not reachable why my while loop shows me an error.

Upvotes: 0

Views: 62

Answers (2)

Fred Mauroy
Fred Mauroy

Reputation: 1229

Looks like you're mixing Javascript and C# in your Razor template. The C# part can't access the varable defined in the Javascript part. Why don't you do everything in C#?

If you want to do that in JS, and if you know all items beforehand, you would need to store all values from your model into a JS array for instance. In that case, the element index would correspond to a local JS variable.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You seem to be trying to mix some server side logic with client side javascript. The element variable is a javascript variable. This means that it exists only on the client. On the other hand the model is a server side concept which doesn't have access to client side variables. So you may consider storing those server side values in a javascript variable if you want to be able to access them:

var values = @Html.Raw(Json.Encode(Enumerable.Range(0, 3).Select(item => Html.DisplayFor(model => model.Address(item).AddressName).ToString())));
for (var i = 0; i < values.length; i++) {
    var obj = document.getElementById('senderAdress' + i);
    var opt = document.createElement('option');
    opt.value = i + 1;
    opt.text = values[i];
}

Of course a much better solution would be to use the strongly typed Html.DropDownListFor server side helper to generate your drop down lists on the server directly.

Upvotes: 1

Related Questions