简体   繁体   中英

How to use Html.EditorFor to initially be read only text box using Razor?

I want to create an output with several rows of data in populated textboxes that are initialy read only, each with an Edit button at the end. This edit would allow that row to become editable while staying on the same page (no new window which is the default with MVC) and then when all edits are complete a submit button at the bottom of the page would save the data to the database. @Html.DisplayFor() will display as read only but to edit this, a new page is created.

If somehow clicking edit could transform that row from @Html.DisplayFor() to @Html.EditorFor() that would be great.

Here's some code snippets:

@model IEnumerable<EnterAdv.Models.Person>
@using (Html.BeginForm()){
<fieldset>
    <table>
        @foreach (var item in Model)
        {
            <tr>
                <td 
                    class="styleDeptNames">@Html.EditorFor(modelItem => item.FirstName) 
                                            @Html.ValidationMessageFor(model => item.FirstName)
                </td>
                <td 
                    class="styleFMLNames">@Html.EditorFor(modelItem => item.LastName)
                                            @Html.ValidationMessageFor(model => item.LastName)
                </td>
                <td class="styleEdit"><input type="button" value="Edit"/></td>     
            </tr>
        }
    </table>
</fieldset>

As you can see right now it's EditorFor() . If this method had an overload that allowed to switch back and forth between read only and edit that would be great but I don't see it. But the bottom line is I have to stay on the same page to edit.

I've been using ActionResult Index() View since it lists the table data.

you can toggle the read only using jquery

$('.clsInput').attr('readonly', 'readonly');

and to remove it

$('.clsInput').removeAttr('readonly');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM