Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 177
  • Last Modified:

Mixing Javascript and C#

HI Experts,

in a Razor View I need the INDEX of the loop mixed in a C# syntax something like:

 
<script type="text/javascript">
...
 $.getJSON("/Controller/Action", { id: val }, function (data) {
           $.each(data, function (index, item) {
                   divbody +=    '<input id="' + selected_id + '" checked="@Model.PaymentTyp[index].Selected" type="checkbox" >' 
            });
 });
...
</script>

Open in new window


what would be the right syntax for that?

thanks.
0
moshik008
Asked:
moshik008
1 Solution
 
shalomcCommented:
Without diving too deep into your code, it seems that you are on the correct path.

C# is executed server side in IIS. For the C# code, Javascript is just text it outputs.
Javascript is executed client side in the browser. For the Javascript code, C# is completely unknown and transparent.

It is your responsibility to write the C# code that prints the correct JS and HTML.

Sometimes things don't work properly, and that's when you will ask EE for help.

Cheers
0
 
louisfrCommented:
Here's a way to do it. I don't know if it's the best in your case, but I think it should work.
<script type="text/javascript">
...
        $.getJSON("/Controller/Action", { id: val }, function (data) {
                $.each(data, function (index, item) {
                        var checked = "";
                        switch(index) {
@for(int i = 0; i<Model.PaymentTyp.Length; i++)
{
    if (Model.PaymentTyp[i].Selected) { <text>case @i:<text> }
}
                                checked = "checked";
                        }
                        divbody +=    '<input id="' + selected_id + '" ' + checked + ' type="checkbox">';
                });
        });
...
</script>

Open in new window

Note that the syntax "checked=true" is not the right one. Use either "checked" alone, or checked='checked'.
0
 
moshik008Author Commented:
Not the cleanest way but hey, it worked.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now