简体   繁体   English

如何在我的视图中访问模型中的属性

[英]How can I access the attributes from my model in my view

I have a model with a Range Attribute on one of the properties:我有一个在其中一个属性上具有范围属性的模型:

using System;
using System.ComponentModel.DataAnnotations;

namespace Example
{
    public class modelClass
    {
        [Range(-1, int.MaxValue)]
        public int property { get; set; }
    }
}

TextBoxFor already accesses the min and max values of the attribute to pass to Jquery validation. TextBoxFor 已经访问了要传递给 Jquery 验证的属性的最小值和最大值。 I would like to be able to access the min and max values of the Range attribute from the view, so that I can set the html 5 min and max attributes as well, rather than hard-coding them as below.我希望能够从视图中访问 Range 属性的最小值和最大值,以便我也可以设置 html 5 min 和 max 属性,而不是将它们硬编码如下。

@using System;
@using Example;
@model modelClass

@Html.TextBoxFor(x => x, new { @type="number", @class = "form-control", min=-1, max=2147483647 })

Here is an idea in how it can be achieved by using Reflection:这是如何通过使用反射来实现的想法:

We add two extra properties to hold the min and max我们添加了两个额外的属性来保存最小值和最大值

public class modelClass
{
    [Range(-1, int.MaxValue)]
    public int property { get; set; }

    public int Min { get; set;}
    public int Max { get; set; }
}

Then in the constructor we do as following:然后在构造函数中,我们执行以下操作:

        RangeAttribute attribute = (RangeAttribute)typeof(modelClass).GetProperty("property").GetCustomAttributes(false).FirstOrDefault();
        this.Min = Convert.ToInt32(attribute.Minimum);
        this.Max = Convert.ToInt32(attribute.Maximum); 

Then in the HTML you can access @Model.Min and @Model.Max.然后在 HTML 中您可以访问@Model.Min 和@Model.Max。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从视图中获得双倍到我的 Model? - How can I get a double from the View into My Model? 如何在我的视图模型中从域服务访问数据? Silverlight 5应用 - How do I access the data from my domain service in my view model ? Silverlight 5 application OnPost之后如何在我的视图中保留模型? - How can I keep my model in my View after OnPost? 如何使用foreach将模型中的属性输入到视图中? - How can I get my properties from a Model into my View with a foreach? 如何在我的视图中仅显示不同的名称(来自模型)? - How can I show just distinct names (from my model) in my view? 如何通过Presenter中的x:Name访问View元素? - How can I access my View elements via x:Name from my Presenter? 在我看来,如何处理代表 model? - How can I handle delegates in my view model? 如何从ActivityTrackingRecord中读取添加到活动中的属性 - How can I read attributes added to my activity from ActivityTrackingRecord ASP.NET MVC 2-如何从下拉菜单中获取选定的值? - ASP.NET MVC 2 - How can I get the selected value from a drop down into my view model? 如何将包含两个列表的模型从视图发送回控制器 - How can i send back a model containing two lists from the view to my controller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM