Skip to content Skip to sidebar Skip to footer

On Click - Make @html.displayfor An Editable Text Field

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. Right n

Solution 1:

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>
<spanclass="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.

Post a Comment for "On Click - Make @html.displayfor An Editable Text Field"