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 b开发者_运维技巧ut 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" })
精彩评论