Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a readonly field in ASP.NET Core

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.

like image 222
serge Avatar asked Aug 23 '17 08:08

serge


2 Answers

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

like image 118
tsu1980 Avatar answered Sep 19 '22 22:09

tsu1980


Output it as HTML with Razor syntax

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor

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

Note - this will need styling appropriately, or wrapping in <span> tag etc...

like image 43
Alex Avatar answered Sep 22 '22 22:09

Alex