1

Model

public int[] mobileid{get;set;}

Script

var k;
for(var i=0;i<3;i++)
{
  [email protected][i];
  alert(k);
}

This method not working,How to assign int array variable to Javascript var. I already use below method:

var k=[];
[email protected](json.Encode(model.mobileid));//not work
8
  • var k = @Html.Raw(Json.Encode(Model.year)) will work fine (I assume you just have some typos (capital H, J and M) Commented Aug 25, 2015 at 11:23
  • var k = @Html.Raw(Json.Encode(Model.year)); End of semicolon (;) showing syntax error Commented Aug 25, 2015 at 11:26
  • Remove the semicolon (see my comment) Commented Aug 25, 2015 at 11:27
  • When remove semicolon ,error showing next line Commented Aug 25, 2015 at 11:29
  • 1
    I now see from your acceptance of the answer (an awful way to solve your problem) that the model was null. You just need to check for null first - if (k) { for(var i=0;i<3;i++) { var x = k[i]; } } Commented Aug 26, 2015 at 1:35

1 Answer 1

2

You can convert your Model.mobileid to a string with a separator of your choice and convert it to a javascript array:

<script>
    var k = "@(Model.mobileid == null ? string.Empty : string.Join(",", Model.mobileid))";
    alert(k);
    k = k.split(",");
    k // k is an array at this point
</script>
Sign up to request clarification or add additional context in comments.

7 Comments

Its work good,But one issue,if(a==b) { var k = "@(string.Join(",", Model.mobileid))";//Now my mobileid is null, alert(k);} if condition is false,but it goes to if block,then show the null reference exception error.
updated my code. You can as well check the value of k after the first line before further operations.
Yep,My model.mobileid is null
model not model.mobileid?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.