从MVC模型制作可读的文本框 [英] Making a text box in mvc readable from model

查看:69
本文介绍了从MVC模型制作可读的文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我与有文本框的视图绑定的模式。现在,他们是我想打只和从模型类读取某些文本框。
因此,任何建议,我怎么可以让他们从模型类的只读。

I have a model which I have binded with a view having text boxes. Now their are certain text boxes which i want to make read only and that to from the model class. So any suggestions how can i make them read only from the model class.

推荐答案

下面就是答案:
视图是一样的东西。

Here is the answer: the View is something like

<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>

我的视图模型是:

My ViewModel is:

public class SampleModel
    {
        [EnableForRole]
        public String Name { get; set; }

        [EnableForRole]
        public DateTime DOB { get; set; }

        [EnableForRole]
        public String Address { get; set; }
    }

和自定​​义元数据属性是这样的:

And the custom Metadata property is like:

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),如:

And now finally you should add the partial view (String.cshtml) in EditorTemplate folder like:

@if (ViewData.ModelMetadata.IsReadOnly)
{
    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
        new {  @readonly = "readonly" })                                     
}
else
{
    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue) 
}

这就是所有。

享受。

这篇关于从MVC模型制作可读的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆