带有参数的ASP.NET MVC Editor-Templates / UIHint

时间:2012-03-13 09:11:05

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我过去一直在使用编辑模板,通过应用以下数据注释:

[UIHint("SomeTemplate")]

视图模型:

 public class MicroViewModel
 {
    public IEnumerable<LabMicro> Micros { get; set; }

    [UIHint("DateTime")]
    public DateTime Date { get; set; }

    public int CaseNo { get; set; }

    [UIHint("SampleTypes")]
    public int LabSampleTypeID { get; set; }

    [UIHint("SampleDetails")]
    public int LabSampleDetailID { get; set; }
 }

如果我想使用特定日期选择器控件而不是常规日期选择器控件,可以按如下方式实现。

示例:

@model DateTime?    
@Html.TextBox("",  String.Format("{0:yyyy-MM-dd}", Model.HasValue ? 
        Model : DateTime.Today), new { @class = "dp", style="width:100px" })

<script type="text/javascript">    
    $(document).ready(function () {    
        $(".dp").datepicker({    
            changeMonth: true,    
            changeYear: true,
            dateFormat: 'yy-mm-dd'    
        });    
    });      
</script>  

对于我的ID字段,我想使用jQuery自动完成组件。

问题:

如何将其他参数传递到UIHintLabSampleTypeID的{​​{1}}部分视图? (因为我想拥有一个自动完成的编辑器 - 模板,例如,它将采用URL和属性名称)

我认为我的自动完成编辑器模板/部分应该是这样的:

LabSampleDetailID

2 个答案:

答案 0 :(得分:73)

您可以使用AdditionalMetadata属性:

[UIHint("DateTime")]
[AdditionalMetadata("foo", "bar")]
public DateTime Date { get; set; }

并在模板中:

@ViewData.ModelMetadata.AdditionalValues["foo"]

所以,如果你想传递一个网址:

[UIHint("DateTime")]
[AdditionalMetadata("controller", "somecontroller")]
[AdditionalMetadata("action", "someaction")]
[AdditionalMetadata("property", "someproperty")]
public DateTime Date { get; set; }

并在您的模板中:

@{
    var values = ViewData.ModelMetadata.AdditionalValues;
}

<script type="text/javascript">
$('.auto').autocomplete({
    source: function (request, response) {
        $.ajax({
            url: '@Url.Action((string)values["action"], (string)values["controller"])',
            dataType: "json",
            data: {
                filter: request.term
            },
            success: function (data) {
                response(
                    $.map(eval(data), function (item) {
                        return {
                            label: item['@values["property"]']
                        }
                    })
                );
            }
        });
    }                    
});
</script>

答案 1 :(得分:5)

您可以使用不带AdditionalMetadata属性的UHint,但需要一些额外的代码

[UIHint("DateTime", null, "key1", "value1", "key2", "value2")]
public DateTime Date { get; set; }

覆盖CreateMetadata:

public class CustomMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        public const string UiHintControlParameters = "UiHintControlParameters";

        protected override ModelMetadata CreateMetadata(
            IEnumerable<Attribute> attributes,
            Type containerType,
            Func<object> modelAccessor,
            Type modelType,
            string propertyName)
        {

            ModelMetadata metadata = base.CreateMetadata(
                attributes,
                containerType,
                modelAccessor,
                modelType,
                propertyName);

            IEnumerable<UIHintAttribute> uiHintAttributes = attributes.OfType<UIHintAttribute>();
            UIHintAttribute uiHintAttribute = uiHintAttributes.FirstOrDefault(a => string.Equals(a.PresentationLayer, "MVC", StringComparison.OrdinalIgnoreCase))
                                              ?? uiHintAttributes.FirstOrDefault(a => String.IsNullOrEmpty(a.PresentationLayer));
            if (uiHintAttribute != null)
            {
                metadata.AdditionalValues.Add(UiHintControlParameters, uiHintAttribute.ControlParameters);
            }

            return metadata;
        }

注册CustomMetadataProvider:

    public static void Application_Start()
    {
        ModelMetadataProviders.Current = new CustomMetadataProvider();
    }

并在您的模板中:

    @{
        IDictionary<string, object> values = (IDictionary<string, object>)
ViewData.ModelMetadata.AdditionalValues[CustomMetadataProvider.UiHintControlParameters];
    }