FrenkyB
FrenkyB

Reputation: 7197

How to use C# string inside jQuery in Razor?

I am using razor view and jQuery. I would like to write value in the razor view into header of modal dialog. (view is opening inside bootstrap modal dialog)

With debugging I've found out that string title is filled with text. But, when modal opens, it is empty.

If I try the same code and write:

$(".modal-title").text("this is just for test");  

everything is fine, text is inside modal dialog header.

Why it is not written from string title?

@model iCommCommon.DTO_CAORAM


@{
    Layout = "~/Views/Shared/LayoutModal.cshtml";

    string title = "Details " + Model.cMEST_CDO2;
}


<script type="text/javascript">    
    $(".modal-title").text(@title);        
</script>

Upvotes: 1

Views: 1104

Answers (2)

TechVision
TechVision

Reputation: 269

Try this one :

<script type="text/javascript">    
   $(function(){
     $(".modal-title").text('@title');   
   });        
</script>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to wrap the value coming from Razor in quotes so that the JS code interprets it as a string:

<script type="text/javascript">    
    $(".modal-title").text('@title');        
</script>

This is obviously assuming that your <script> tag is at the end of the <body>, otherwise you will also need to wrap the jQuery code in a document.ready event handler.

Upvotes: 4

Related Questions