0

I have this rows of c# code in View razor page:

@{
    List<UserContact> userContacts = ViewBag.contacts;
    String contacts = Html.Partial("~/Views/Shared/Contacts.cshtml", userContacts).ToHtmlString();
}

I want to use the content of contacts variable in JavaScript function since the contacts is a C# object I cant use this variable in JavaScript function.

Is there any way to use contacts variable in Javascript function? Maybe since the type is string it can be converted to JavaScript variable?

1
  • 3
    in a script: var partialHtml = '@contacts'; Commented Oct 23, 2014 at 12:53

2 Answers 2

3

You can use @ directives like you would normally do. You can print it using Html.Raw:

var x = /* this is javascript */
@{
    ...

    @Html.Raw(contacts)
}

Or just call @Html.Partial directly:

var x = /* this is javascript */
@{
    ...

    @Html.Partial(...)
}

Or declare it here:

@{
    ...

    string contacts = @Html.Partial(...)
}

And use it later:

@contacts
Sign up to request clarification or add additional context in comments.

1 Comment

I need to pass the content of the contacts object to the parent view razor page, for this purpose I need to convert the C# object to JavaScript object.
3

Yes there is, you only need to render it inside a script block. Try this:

<script>

    var contacts = '@contacts';
    alert(contacts);

</script>

Comments

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.