Using Editable attribute on MVC 3 view model

后端 未结 5 1683
故里飘歌
故里飘歌 2020-12-10 05:58

I\'m looking to use attributes to mark view model properties as readonly so that the view fields are read only in the rendered view. Applying System.ComponentModel.DataAnnot

5条回答
  •  有刺的猬
    2020-12-10 06:33

    Found that the use of Editable instead Readonly on the model works exactly the same.

    [ReadOnly(true)] //or
    [Editable(false)]
    public string Name { get; set; }
    

    This syntax does work when interrogating a property attribute on the view itself. Also works when attribute is Editable(true)

    @if (ViewData.ModelMetadata.Properties.Where(p => p.PropertyName == "Name").First().IsReadOnly)
    { 
        @Html.TextBoxFor(model => model.Name, new { style = "width:190px; background-color: #ffffd6", @readonly =  "readonly" })
    } 
    else
    {
        @Html.TextBoxFor(model => model.Name, new { style = "width:190px; " })
    }
    

    Using an editor template here a simple string template:

    @model String
    @{
    IDictionary htmlAttributes = new Dictionary();
    if (ViewData.ModelMetadata.IsReadOnly) //this will be looking at the actual property not the complete model
    {
    htmlAttributes.Add("style", "width:100px; background-color:#ffffd6");
    htmlAttributes.Add("readonly", "readonly");
    @Html.TextBox("", Model, htmlAttributes)
    }
    

提交回复
热议问题