brusli
brusli

Reputation: 63

Passing a value(string) form razor model to JS with onclick attribut

This is my html

@model MarketingPhoneBook.Models.Responses.ContactLogResponse
@{
    Layout = "";
}
<form method="post" id="idForm" action="/Home/CreateLog">
    <div class="form-group">
        @{
            var mystring = Html.Raw(Model.NewLog.CallLogText);
        }
        @Html.LabelFor(model => model.NewLog.CallLogText, htmlAttributes: new { @class = "control-label " })
        <div onclick="addDate('@mystring')">
            @Html.TextAreaFor(model => model.NewLog.CallLogText, new { @class = "", @style = "width: 100%; max-width: inherit;", @rows = "15", @onblur = "save()", @type = "submit" })
            @Html.ValidationMessageFor(model => model.NewLog.CallLogText, "", new { @class = "text-danger" })
        </div>
    </div>
    @Html.HiddenFor(model => model.NewLog.ContactId)

</form>

and this is my js function

function addDate(text) {
    return text = new Date() + " " + text;
}

Model.NewLog.CallLogText is of type string. Onclick event does not get triggered

Upvotes: 0

Views: 705

Answers (2)

Nehang Shah
Nehang Shah

Reputation: 1

Below code works for me. I am using it in Nop commerce 4.70 which is based on asp .net core 8.

I can even able to send string and Html data using it.

<a onclick="openVideoModal('@Html.Raw(JavaScriptEncoder.Default.Encode(Model.Sections[i].Lessons[j].VideoUrl))')" class="btn btn-sm btn-success mb-0">Play</a>

Upvotes: 0

SᴇM
SᴇM

Reputation: 7213

Use HttpUtility.JavaScriptStringEncode Method to encode string before passing to JS:

@{
    var mystring = Html.Raw(HttpUtility.JavaScriptStringEncode(Model.NewLog.CallLogText));
}

Upvotes: 1

Related Questions