テキストボックスを持つビューにバインドしたモデルがあります。今、それらは私が読み取り専用にしたい特定のテキストボックスであり、それはモデルクラスからのものです。したがって、モデルクラスからのみ読み取るようにする方法を提案してください。
2 に答える
            1        
        
		
ReadOnlyMVC 2 または MVC 1 では動作しませんが、3 & 4 (ベータ) では動作しています。
モデルから、以下のように使用できます。
 [ReadOnly(true)]
 public bool IsAdmin { get; set; }
    于 2012-10-30T10:54:49.203   に答える
    
    
            0        
        
		
答えは次のとおりです。ビューは次のようなものです
<div>
    <table>
        <tr>
            <td>@Html.LabelFor(x => x.Name)</td>
            <td>@Html.EditorFor(x => x.Name)</td>
        </tr>
        <tr>
            <td>@Html.LabelFor(x => x.DOB)</td>
            <td>@Html.EditorFor(x => x.DOB)</td>
        </tr>
        <tr>
            <td>@Html.LabelFor(x => x.Address)</td>
            <td>@Html.EditorFor(x => x.Address)</td>
        </tr>
    </table>
</div>
私のViewModelは次のとおりです。
public class SampleModel
    {
        [EnableForRole]
        public String Name { get; set; }
        [EnableForRole]
        public DateTime DOB { get; set; }
        [EnableForRole]
        public String Address { get; set; }
    }
カスタム メタデータ プロパティは次のようになります。
public class EnableForRoleAttribute : Attribute, IMetadataAware
    {
        public void OnMetadataCreated(ModelMetadata metadata)
        {
            var toEnable = IsAccessible(metadata.PropertyName);
            metadata.IsReadOnly = !toEnable;
        }
        private bool IsAccessible(String actionName)
        {            
            return HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.IsInRole(roleName); //if you use MembershipProvider
        }
    }
そして最後に、次のように EditorTemplate フォルダーに部分ビュー (String.cshtml) を追加する必要があります。
@if (ViewData.ModelMetadata.IsReadOnly)
{
    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
        new {  @readonly = "readonly" })                                     
}
else
{
    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue) 
}
それで全部です。
楽しみ。
于 2012-10-30T11:05:15.533   に答える