You're getting confused about the execution. The
if
statement is a Javascript statement, which executes on the client. The
@Html.Raw(...)
statement is a Razor statement, which executes on the server.
The client-side
if
block cannot alter the code that executes on the server.
If you want to control whether the server-side statement executes, you will need to use a server-side condition. In order to tell the compiler that the content within the server-side block is client-side code, you will need to wrap it in a
<text>...</text>
block:
$(function(){
@if (Model.Option == "Email File Links" || Model.Option == "Email Files")
{
<text>
const strDesc = @Html.Raw(Json.Encode(Model.EmailModel?.EmailBody));
if (strDesc) {
myRichText.summernote('editor.pasteHTML', '<span>' + strDesc + '</span>');
}
</text>
}
});
Since you have no other script in the handler, I'd be inclined to omit the handler if the condition is not met:
@if (Model.Option == "Email File Links" || Model.Option == "Email Files")
{
<text>
$(function(){
const strDesc = @Html.Raw(Json.Encode(Model.EmailModel?.EmailBody));
if (strDesc) {
myRichText.summernote('editor.pasteHTML', '<span>' + strDesc + '</span>');
}
});
</text>
}
NB: The
$(document).ready(...)
syntax has been deprecated since jQuery 3.0:
jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:
$( handler )
$( document ).ready( handler )
$( "document" ).ready( handler )
$( "img" ).ready( handler )
$().ready( handler )
As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated. This is because the selection has no bearing on the behavior of the .ready()
method, which is inefficient and can lead to incorrect assumptions about the method's behavior. For example, the third syntax works with "document" which selects nothing. The fourth syntax waits for the document to be ready but implies (incorrectly) that it waits for images to become ready.