1

My view generates some js code. I need to cast my Model to interface type to get some properties.

Here is an example:

<script type="text/javascript" language="javascript">
var js_array = [];
@for (var i = 0; i < ( Model as MyProject.Models.IMyInterface ).PropertyList.Count; i++) {
    <text>
        js_array['@( Model as MyProject.Models.IMyInterface ).PropertyList[i].id'] = {};
    </text>
}
</script>

I got:

<script type="text/javascript" language="javascript">
var js_array = [];
js_array['MyProject.Models.MyModelType.PropertyList[i].id'] = {};
js_array['MyProject.Models.MyModelType.PropertyList[i].id'] = {};
js_array['MyProject.Models.MyModelType.PropertyList[i].id'] = {};
js_array['MyProject.Models.MyModelType.PropertyList[i].id'] = {};
js_array['MyProject.Models.MyModelType.PropertyList[i].id'] = {};
js_array['MyProject.Models.MyModelType.PropertyList[i].id'] = {};
js_array['MyProject.Models.MyModelType.PropertyList[i].id'] = {};
js_array['MyProject.Models.MyModelType.PropertyList[i].id'] = {};
</script>

But I need:

<script type="text/javascript" language="javascript">
var js_array = [];
js_array['1'] = {};
js_array['2'] = {};
js_array['3'] = {};
js_array['4'] = {};
js_array['5'] = {};
js_array['6'] = {};
js_array['7'] = {};
js_array['8'] = {};
</script>

As you can see this display type instead of value...

Can you tell me why and how can I fix it?

1
  • 1
    The reason why is because the @() is a special block that only parses what's contained in the (). Your code has only the class in the () and so it calls ToString on the class and then the .PropertyList... is assumed to be just regular output because it's no longer under control of the @. Commented Jul 22, 2011 at 16:17

1 Answer 1

4

It seems you're missing a couple of parentheses.

@for (var i = 0; i < ( Model as MyProject.Models.IMyInterface ).PropertyList.Count; i++) {
    <text>
        js_array['@( (Model as MyProject.Models.IMyInterface).PropertyList[i].id )'] = {};
    </text>
}

I would make it a bit more readable like:

@foreach ( var property in ((MyProject.Models.IMyInterface)Model).PropertyList ) {
    <text>
        js_array['@(property.id )'] = {};
    </text>
}

And if your model implements the interface then you don't even need the cast, making it:

@foreach ( var property in Model.PropertyList ) {
    <text>
        js_array['@(property.id)'] = {};
    </text>
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.