Michael
Michael

Reputation: 13616

Using C# object in razor view page

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?

Upvotes: 0

Views: 1271

Answers (2)

Patrick Hofman
Patrick Hofman

Reputation: 156938

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

Upvotes: 3

Thomas C. G. de Vilhena
Thomas C. G. de Vilhena

Reputation: 14545

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

<script>

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

</script>

Upvotes: 3

Related Questions