Display a readonly field in ASP.NET Core

serge picture serge · Aug 23, 2017 · Viewed 19.6k times · Source

I am new in ASP.NET Core and would like to ask about displaying a field in w a view. I have a

class Person { 
    public string Name {get; set;} 
    public string Nickname {get; set;} 
}

Typically, in the EditPerson View, I do

<input asp-for="Name" class="form-control" />
<input asp-for="Nickname" class="form-control" />

to display the fields.

But in my EditPerson View I need to display Name as readonly, and Nickname as editable field.

The Name should not be in a textbox(even readonly), but rather in a label or div...

Is there a standard approach to display such fields?

I don't want that the field to be updated back to the model or DB, I need only reading the field.

Answer

tsu1980 picture tsu1980 · Mar 7, 2018

Try this.

<input asp-for="Name" class="form-control" readonly="@(true)">
<input asp-for="Name" class="form-control" readonly="@(false)">

This render:

<input class="form-control" type="text" id="Name" name="Name" value="Tom" readonly="readonly">
<input class="form-control" type="text" id="Name" name="Name" value="Tom">

I realized it from here: https://github.com/aspnet/Mvc/issues/7333#issuecomment-363504164