简体   繁体   中英

Template Question in asp.net mvc

I have a few questions.

I want to make my textbox readonly so I put [ReadOnly(true)] on my view model but the textbox does not have the readonly tag in it.

public class ViewModel()
{
   [HiddenInput(DisplayValue = false)]
   [ReadOnly(true)]
   public int Id { get; set; }
}

in my razor page I got

@Html.EditorFor(x => x.Id)

I also noticed that when I use EditorFor it add classes like "text-box single-line". Is there away I can stop these from being generated or add my own class names to it?

Finally can you use a meta tag to tell the EditrFor to be empty instead of placing a value in it. Like in my cause it puts zero since that what the int holds. What if I just want it too look blank?

I am confused as to exactly what you want. You are asking if you can have a readonly field that does not display the actual value of the bound property? I assume you want the Id in your View so that when you post back you still have the value? If this is correct then just use a hidden field;

@Html.HiddenFor(model => model.Id)

That way when your form is posted back it will still bind the Id to model in the Controller

You could create a custom editor for Int32 data types and easily point that property to the new editor with a Data annotation, and could do for all other Int values that you want to display in a similar manner throughout the application (keeping it nice and DRY). Your existing ViewModel class would change to this:

public class ViewModel()
{
   [UIHint("ReadonlyInt")]
   [ReadOnly(true)]
   public int Id { get; set; }
}

And then you create a simple new partial view under Views\\Shared\\EditorTemplates called ReadonlyInt.cshtml

like this:

@model System.Int32?

@Html.TextBox("", Model.GetValueOrDefault().ToString(), new { disabled = "disabled" })

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