English 中文(简体)
如何读取财产数据说明价值。 NET MVC
原标题:How to read property data annotation value in .NET MVC

I Just starting out w/ ASP.NET MVC 3 and I am trying to render out the following HTML for the string properties on a ViewModel on the create/edit view.

<input id="PatientID" name="PatientID" placeholder="Patient ID" type="text" value="" maxlength="30" />

每种价值都与GisModel、id &的财产相重;名称为财产名称,持有人为显示属性,价值为财产价值,最大程度为StingLength属性。

Instead of typing out the above HTML w/ the correct values for each of my string properties I thought I would try to create an EditorTemplate by the name of SingleLineTextBox and use UIHint on my string properties or pass the name of the view when I call EditFor. So far so good, except I can t figure out how to get the maxlength value off the StringLength attribute.

这里是我迄今为止制定的法典:

<input id="@ViewData.ModelMetadata.PropertyName" name="@ViewData.ModelMetadata.PropertyName" placeholder="@ViewData.ModelMetadata.DisplayName" type="text" value="@ViewData.Model" maxlength="??" />

As you can see, not sure how to set maxlength value. Anyone know how?

Also, am I going about this the best way? As I said before I could just write out the plain HTML myself for each property on the page. I ve looked at using TextBoxFor it wasn t setting the maxlength and was adding a bunch of validation markup to the HTML output because of the StringLength attribute which I do not want. Another option I saw was extensions/helpers off the HTML class.

最佳回答

不用<代码>StringLength属性(因为其为有效提供人,而不是元数据提供人),你可以使用<代码>。 样本使用:

public class ViewModel
{
    [AdditionalMetadata("maxLength", 30)]
    public string Property { get; set; }
}

Basically it puts the value 30 under the key maxLength in the ViewData.ModelMetadata.AdditionalValues dictionary. So you can use it your EditorTemplate:

<input maxlength="@ViewData.ModelMetadata.AdditionalValues["maxLength"]" id="@ViewData.ModelMetadata.PropertyName" name="@ViewData.ModelMetadata.PropertyName" placeholder="@ViewData.ModelMetadata.DisplayName" type="text" value="@ViewData.Model"  />
问题回答

t瓦福松回答的全代码样本:

模式:

public class Product
{
    public int Id { get; set; }

    [MaxLength(200)]
    public string Name { get; set; }

EditorTemplatesString.cshtml

@model System.String
@{
    var metadata = ViewData.ModelMetadata;
    var prop = metadata.ContainerType.GetProperty(metadata.PropertyName);
    var attrs = prop.GetCustomAttributes(false);

    var maxLength = attrs.OfType<System.ComponentModel.DataAnnotations.MaxLengthAttribute>().FirstOrDefault();
}
<input [email protected]()@(metadata.IsRequired ? " required" : "")@(maxLength == null ? "" : " maxlength=" + maxLength.Length) />

超文本产出:

<input id=Name maxlength=200 />

但它运作得很快。 我现在要提一下,将其清理起来。 助教:

public static class EditorTemplateHelper
{
    public static PropertyInfo GetPropertyInfo(ViewDataDictionary viewData)
    {
        var metadata = viewData.ModelMetadata;
        var prop = metadata.ContainerType.GetProperty(metadata.PropertyName);
        return prop;
    }

    public static object[] GetAttributes(ViewDataDictionary viewData)
    {
        var prop = GetPropertyInfo(viewData);
        var attrs = prop.GetCustomAttributes(false);
        return attrs;
    }

    public static string GenerateAttributeHtml(ViewDataDictionary viewData, IEnumerable<Delegate> attributeTemplates)
    {
        var attributeMap = attributeTemplates.ToDictionary(t => t.Method.GetParameters()[0].ParameterType, t => t);
        var attrs = GetAttributes(viewData);

        var htmlAttrs = attrs.Where(a => attributeMap.ContainsKey(a.GetType()))
            .Select(a => attributeMap[a.GetType()].DynamicInvoke(a));

        string s = String.Join(" ", htmlAttrs);
        return s;
    }
}

Editor Template:

@model System.String
@using System.ComponentModel.DataAnnotations;
@using Brass9.Web.Mvc.EditorTemplateHelpers;
@{
    var metadata = ViewData.ModelMetadata;

    var attrs = EditorTemplateHelper.GenerateAttributes(ViewData, new Delegate[] {
        new Func<StringLengthAttribute, string>(len => "maxlength=" + len.MaximumLength),
        new Func<MaxLengthAttribute, string>(max => "maxlength=" + max.Length)
    });

    if (metadata.IsRequired)
    {
        attrs.Add("required");
    }

    string attrsHtml = String.Join(" ", attrs);
}
<input type=text [email protected]() @attrsHtml />

因此,你通过一系列代表,每次使用<代码>Func<AttributeTypeGoes 这里,“扼制”;,然后回去你为每一特性所希望的任何超文本。

这实际上很错,你只能描绘你所关心的属性,你可以绘制同一种超文本不同部分的不同组别的图,最后使用(如<代码>@attrsHtml)对模板的重读性。

为了做到这一点,你必须建立自己的HtmlHelper延伸期,并利用思考来掌握模型财产的属性。 http://codeplex.com/aspnet/rel=“nofollow”http://codeplex.com/aspnet, 现有。 你们需要利用作为论据的表达方式,将财产信息输入模型财产。 他们有几门辅助班,可作为这方面的模板。 之后,使用“GetCustomAttributes”方法查找StingLength属性并提取其价值。 由于你正在使用塔格布克尔来制作这些投入,因此通过塔格布代尔德添加时间段作为特性。

   ...

   var attribute = propInfo.GetCustomAttributes(typeof(StringLengthAttribute),false)
                           .OfType<StringLengthAttribute>()
                           .FirstOrDefault();
   var length = attribute != null ? attribute.MaximumLength : 20; //provide a default
   builder.Attributes.Add("maxlength",length);

   ...

   return new MvcHtmlString( builder.ToString( TagRenderMode.SelfClosing ) );
}

见我关于为何我认为这是一个坏想法的评论。

更简单的解决办法是实施一个海关编码。 类似:

internal class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        ModelMetadata modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

        var maxLengthAttribute = attributes.OfType<MaxLengthAttribute>().SingleOrDefault();
        if (maxLengthAttribute != null)
        {
            modelMetadata.AdditionalValues.Add("maxLength", maxLengthAttribute.Length);
        }
        return modelMetadata;
    }
}

在模板中,你只能使用:

object maxLength;
ViewData.ModelMetadata.AdditionalValues.TryGetValue("maxLength", out maxLength);

www.un.org/Depts/DGACM/index_french.htm 举例说:

我根据以上条款使用和测试的,可参见下文的答复(,与MVC 5 测试,EF)。 6)

ASP.NET MVC 3 - Data Annoation and Max Length/Size for Textbox Rendering

如果没有具体,我个人会取得一些好坏参半的结果,试图实施其他一些方法,我也没有发现,要么声称采用的方法太长了;然而,我确实认为,其他一些方法中有一些是看不到的。

@using System.ComponentModel.DataAnnotations
@model string
@{
    var htmlAttributes = ViewData["htmlAttributes"] ?? new { @class = "checkbox-inline" };

    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

    if (!attributes.ContainsKey("maxlength"))
    {
        var metadata = ViewData.ModelMetadata;
        var prop = metadata.ContainerType.GetProperty(metadata.PropertyName);
        var attrs = prop.GetCustomAttributes(false);
        var maxLength = attrs.OfType<MaxLengthAttribute>().FirstOrDefault();
        if (maxLength != null)
        {
            attributes.Add("maxlength", maxLength.Length.ToString());
        }
        else
        {
            var stringLength = attrs.OfType<StringLengthAttribute>().FirstOrDefault();

            if (stringLength != null)
            {
                attributes.Add("maxlength", stringLength.MaximumLength.ToString());
            }
        }
    }

}

@Html.TextBoxFor(m => m, attributes)




相关问题
Using jquery to get a partial view and updating the UI

I need to render a partial view (returned from the controller) to show some customer summary details. This will need to happen when the user clicks on a button. In the the mean time the user can ...

MVC 2 / MVC 3 / MVC 4

MVC 2 我们可以轻松地创造领域。 现在,我的问题涉及nes地区(地区内)。

Asp.Net MVC 2 - Changing the PropertyValueRequired string

Using a resx file in the App_GlobalResources directory, I ve been able to change the default message for the PropertyValueInvalid string of the model validators. But it doesn t work to translate the ...

ASP.NET MVC 3 - What features do you want to see? [closed]

I know a bunch of people that are really enjoying the improvements that ASP.NET MVC 2 made over the first release. I have just started to migrate our MVC 1 project over and so far areas has totally ...