在 TextAreaFor 中保存文本的独立于浏览器的方法

Browser-independent way to save text in a TextAreaFor

使用 ASP.NET MVC,我有一个包含 TextAreaFor 的视图,我希望用户能够在其中输入一些注释并即时保存它们,查看之前保存在那里的注释(无论是他们还是其他用户),以及修改现有注释(例如添加其他注释)。这就是我所拥有的....

视图中的 div:

    <div class="form-group">
        <label for="InternalNotes" class="control-label">Internal Notes</label>
        @Html.TextAreaFor(w => w.InternalNotes, new { @class = "form-control" , @id="notes" })  @*this is editable*@
    </div>
    <div class="form-group">
        <div class="col-xs-6">
            <button type="button" id="savenotes" class="btn btn-default btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save Request Notes</button>
            <div style="color:green; display:none" id="notessuccess">Notes successfully saved</div>
            <div style="color:red; display:none" id="noteserror">Notes unable to be saved</div>
        </div>
        <div class="col-xs-6 text-right">
            <button type="submit" id="deletereq" class="btn btn-default btn-primary" value="delete" name="submit"><span class="glyphicon glyphicon-remove"></span> Delete Request</button>
        </div>
    </div>

所以用户可以在 TextAreaFor 中输入一些内容,然后点击 "savenotes" 按钮,这应该会通过 Ajax 保存它们。这是 jQuery 的:

$(document).ready(function () {

    $("#savenotes").click(function () {

        $("#notessuccess").hide();
        $("#noteserror").hide();

        var id = @Model.AccessRequestId;
        var notes = document.getElementById("notes").textContent;  //innerText;

        $.ajax({
            data: { 'id': id, 'notes': notes },
            type: 'POST',
            //contentType: "application/json; charset=utf-8",
            url: '/Administration/SaveRequestNotes',
            success: function (data) {
                if (data.success == "ok") {
                    $("#notessuccess").fadeIn();
                } else {
                    $("#noteserror").fadeIn();
                }
            },
            fail: function (data) {
                $("#noteserror").fadeIn();
            }
        });
    });
});

"innerText" 被注释掉了,因为那是我最初使用的,但它只在 Internet Explorer 中工作 - 另一个用户正在使用 Chrome,在那里他可以看到其他用户的注释已经在那里了,但是当他试图在他们的笔记之外保存笔记时,它会把它全部炸掉,所以笔记会变成空的!

所以我改成了"textContent"。这在 Internet Explorer 中仍然有效,但现在在 Chrome 和 Firefox 中虽然它不会清空现有笔记,但它仍然不会保存添加的新笔记。什么是独立于浏览器的方式,我可以使这项工作正常进行,以便每个人的笔记都能得到正确保存,无论他们使用什么?

谢谢!

您可以使用 jQuery val() 方法获取用户输入到文本区域的文本

var notes = $("#notes").val();
alert(notes);

您也可以考虑使用 Url.Action 辅助方法来生成您的操作方法的正确相对路径。

 url: '@Url.Action("SaveRequestNotes","Administration")',