通过 onclick 属性将值(字符串)表单 razor 模型传递给 JS

问题描述 投票:0回答:2

这是我的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>

这是我的js函数

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

Model.NewLog.CallLogText 是字符串类型。 Onclick 事件没有被触发

javascript c# razor model-view-controller
2个回答
1
投票

在传递给 JS 之前使用 HttpUtility.JavaScriptStringEncode 方法 对字符串进行编码:

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

0
投票

下面的代码对我有用。我在基于 asp .net core 8 的 Nop commerce 4.70 中使用它。

我什至可以使用它发送字符串和 Html 数据。

<a onclick="openVideoModal('@Html.Raw(JavaScriptEncoder.Default.Encode(Model.Sections[i].Lessons[j].VideoUrl))')" class="btn btn-sm btn-success mb-0">Play</a>
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.