On Click - Make @Html.DisplayFor an editable text field

前端 未结 1 1134
不思量自难忘°
不思量自难忘° 2021-01-26 19:27

So I am playing with a practice site I made and I want to attempt a feature that will allow me to select any data value in the table, edit it, then save it to the Database.

相关标签:
1条回答
  • 2021-01-26 20:02

    In your Razor template, you will need both an @Html.DisplayFor(...) and an @Html.EditorFor(...). The text field should be hidden, and upon clicking the display text, JavaScript needs to hide the display text and show the text field, then set focus to it:

    <span class="item-display">
        @Html.DisplayFor(modelItem => modelItem.Description)
    </span>
    <span class="item-field">
        @Html.EditorFor(modelItem => modelItem.Description)
    </span>
    

    Some CSS:

    .item-field: {
        display: none;
    }
    

    And some jQuery for good measure:

    $(document.documentElement)
        .on("click", "span.item-display", function(event) {
            $(event.currentTarget)
                .hide()
                .next("span.item-field")
                .show()
                .find(":input:first")
                .focus()
                .select();
        })
        .on("keypress", "span.item-field", function(event) {
            if (event.keyCode != 13)
                return;
    
            event.preventDefault();
    
            var $field = $(event.currentTarget),
                $display = $field.prev("span.item-display");
    
            $display.html($field.find(":input:first").val());
            $display.show();
            $field.hide();
        });
    

    JSFiddle: http://jsfiddle.net/A3bg6/1/

    When pressing ENTER on the text field, it will hide the field and show the display, plus update the display.

    0 讨论(0)
提交回复
热议问题