【问题标题】:Browser-independent way to save text in a TextAreaFor在 TextAreaFor 中保存文本的独立于浏览器的方式
【发布时间】:2018-03-04 10:38:50
【问题描述】:

使用 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,在那里他可以看到其他用户已经存在的笔记,但是当他' d 尝试保存除了他们的笔记之外的笔记,它会全部炸毁,所以笔记将是空的!

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

谢谢!

【问题讨论】:

    标签: ajax asp.net-mvc text cross-browser textarea


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 看起来使用 .val() 有效。呃,我不知道为什么我以前没想过使用它....我认为它会像那样愚蠢!只是想知道使用@Url.Action 比使用我现在拥有的更好吗?
    • 它会创建正确的相对路径,而与您的网址无关。
    猜你喜欢
    • 2020-09-04
    • 1970-01-01
    • 2018-05-13
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 2022-07-01
    • 1970-01-01
    相关资源
    最近更新 更多