When Building A Datagrid Helper How To Access The New Data Annotation Attributes Using Reflection

Feb 3, 2010

So I've eagerly added the System.ComponentModel.DataAnnotations namespace to my model.

I've added things such as:

[Required] [DisplayName("First Name")]
public string first_name {get;set;}

I really like these attributes because they save me from having to write custom T4 and/or modify views heavily. This way, I can regenerate a view confident that it will add the display names I want, etc.

The problem comes in when I started building a DataGrid helper inspired by the one in ASP.NET MVC2 unleashed. In this helper, Stephen uses reflection to get at the column headings.

var value=typeOf(T).GetProperty(columnName).GetValue(item,null) ?? String.Empty;

Well, the trouble is I don't want to retrieve the property name. I want to retrieve the value for the DisplayName attribute.

My first attempt at this was to look inside the Attributes property of the PropertyInfo class. Unfortunately, none of the data annotations show up as an attribute.

Is there a way to retrieve the data annotations using reflection?

View 2 Replies


Similar Messages:

MVC 3. Data Annotation Attributes Are Not Woking

Feb 1, 2011

I've just installed MVC 3 and have the following problem. Even if I try to run the sample project, that is included in MVC 3 installation, when I go to the Register form, only the Required attribute causes validation. The Email Format attribute doesn't work,which means I can enter non-email string into the email field and it submits the form without any error messages.

View 6 Replies

MVC :: To Put The Data Annotation Attributes - On The Viewmodel Classes Or On The Model?

Mar 20, 2010

I am using a model but as I want to have clean views I use the viewmodel approach which is like a downsized model which I map in my controller actions before sending to the view or getting it back in a HttpPost attributed action.

My question is: where to put the data annotation attributes. On the viewmodel classes or on the model? If I get it clearly the viewmodel annotations are used for the client side generation of validation right?

Do does that mean I have to put data annotations everywhere on both model and viewmodel?

View 11 Replies

Data Annotation Attributes Not Working Using Buddy Class Metadata In An MVC App?

Oct 7, 2010

I have found hints that MVC 2 recognises the 'buddy class' type of property metadata, where data annotation attributes are applied to a 'buddy' metadata class, and the MetadataType on the actual entity class points to that buddy class, as below. However, as below, it seems the only attribute that makes any difference to the rendered UI is DisplayName. Why are the other attributes like DataType, Required, and ReadOnly not working? I.e. why can I enter text in a read only field? Why do I not get an error when a required field is empty? Why does the DataType attribute have no apparent effect? Why does EditorForModel not include validation messages?

[MetadataType(typeof(CustomerMetadata))]
public partial class Customer
{
public class CustomerMetadata
{
[ScaffoldColumn(false)]
public object CustomerId { get; set; }
[DisplayName("CustomerNo.")]
[ReadOnly(true)]
[Required(AllowEmptyStrings = false, ErrorMessage = "Customer No. is required.")]
public object CustomerNo { get; set; }
}
}

I find behaviour the same whether I use an explicit LabelFor and TextBoxFor for each model property, or a single EditorForModel for the whole model.

View 2 Replies

C# - Set Attributes Values Using Reflection?

Jan 29, 2010

I have a class decorated with a attribute ...[DataEntity("MESSAGE_STAGING", EnableCaching = true, CacheTimeout = 43200)] for some requirement,I want to change this value "MESSAGE_STAGING" at run time to "Test_Message_Staging". What is the best possible way to achieve this? Can i use reflection ,Or is there any other way to do this.

View 3 Replies

MVC - Find Controllers With (Authorize) Attributes Using Reflection In C# Or Build Dynamic Site.Master Menus?

Jun 8, 2010

I'm currently writing a web app in ASP.NET MVC 1.0 (although I do have MVC 2.0 installed on my PC, so I'm not exactly restricted to 1.0) -- I've started with the standard MVC project which has your basic "Welcome to ASP.NET MVC" and shows both the [Home] tab and [About] tab in the upper-right corner. Pretty standard, right? I've added 4 new Controller classes, let's call them "Astronomer", "Biologist", "Chemist", and "Physicist". Attached to each new controller class is the [Authorize] attribute. For example, for the BiologistController.cs

[Authorize(Roles = "Biologist,Admin")]
public class BiologistController : Controller
{
public ActionResult Index() { return View(); }
}

These [Authorize] tags naturally limit which user can access different controllers depending on Roles, but I want to dynamically build a Menu at the top of my website in the Site.Master Page based on the Roles the user is a part of. So for example, if "JoeUser" was a member of Roles "Astronomer" and "Physicist", the navigation menu would say:

[Home] [Astronomer] [Physicist]
[About]

And naturally, it would not list links to "Biologist" or "Chemist" controller Index page. Or if "JohnAdmin" was a member of Role "Admin", links to all 4 controllers would show up in the navigation bar. Ok, you prolly get the idea... Now for the real question... Starting with the answer from this StackOverflow topic about Dynamic Menu building in ASP.NET, I'm trying to understand how I would fully implement this. (I'm a newbie and need a little more guidance, so please bare with me.) The answer proposes Extending the Controller class (call it "ExtController") and then have each new WhateverController inherit from ExtController.

My conclusion is that I would need to use Reflection in this ExtController Constructor to determine which Classes and Methods have [Authorize] attributes attached to them to determine the Roles. Then using a Static Dictionary, store the Roles and Controllers/Methods in key-value pairs. I imagine it something like this:

public class ExtController : Controller
{
protected static Dictionary<Type,List<string>> ControllerRolesDictionary;
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
// build list of menu items based on user's permissions, and add it to ViewData
IEnumerable<MenuItem> menu = BuildMenu();
ViewData["Menu"] = menu;
}
private IEnumerable<MenuItem> BuildMenu()
{
// Code to build a menu
SomeRoleProvider rp = new SomeRoleProvider();
foreach (var role in rp.GetRolesForUser(HttpContext.User.Identity.Name))
{
}
}
public ExtController()
{
// Use this.GetType() to determine if this Controller is already in the Dictionary
if (!ControllerRolesDictionary.ContainsKey(this.GetType()))
{
// If not, use Reflection to add List of Roles to Dictionary
// associating with Controller
}
}
}

Is this doable? If so, how do I perform Reflection in the ExtController constructor to discover the [Authorize] attribute and related Roles (if any) ALSO! Feel free to go out-of-scope on this question and suggest an alternate way of solving this "Dynamic Site.Master Menu based on Roles" problem. I'm the first to admit that this may not be the best approach.

View 2 Replies

Access :: Data Access Class / Helper Class For Access Databases?

Mar 15, 2011

recommend a data access class / helper class for Access databases, similar to the sqlhelper class found in the (Data Access Application Block)?

View 6 Replies

ADO.NET :: Building Data Access Layer In 3.5

Aug 25, 2010

In old style i used to return datasets to BOL (From DAL) and then to Website. but in 3.5 is there any new way to construct DAL. i heard about returning List<> is better than DataSet. I Got to build new DAL for my new project. if i should go for List <> aprroach can i use Linq to Sql technique or shall i go for execute dataset (using applicatio block libraries) and then fill data in List<> prior to return it back to BOL.

View 1 Replies

C# - Building A Datagrid To Show Different Tables Depending On Request.QueryString?

Apr 30, 2010

I have a control with a datagrid in it and I was wondering if depending on the value I get back from the a Request.QueryString if I could set the table name to that (that is the value being sent) and then have it build the columns?

I have about 3 different tables, and they have different amounts of columns, and of course with different names.

View 1 Replies

C# - How To Access A Child Datagrid Which Is Inside Of Another Datagrid, Before It's Not Binded

Jun 23, 2010

I have a nested datagrid. I want to get header texts of child datagrid, bifore binding process.

Is there a way to do this?

View 1 Replies

Forms Data Controls :: How To Access The Values From Datagrid

Jan 1, 2010

I am creating a web page where i need to enter maks for the student of a class. So i queried the students regno from the database and bind it to the datagrid and i've added a template column which contains the textbox to enter the marks of the student...

The problem i face here is whenever i take the value from the textbox(template column) using theFINDCONTROL it returns only the NULL string...i have given here my code

[Code]....

the value is null even if we enter some values in the textbox

View 10 Replies

MVC :: Data Annotation Add And Edit Mode

Jun 23, 2010

i have a field username which i want to have as a label in the edit.aspx and as a typical textbox in create.aspx . i have applied datannotation class . how would i do that. in the edit mode it is always going model.isvalid ==false . so what i did had a textbox there with the label and hid it . it is working fine now . but is there any clean way this is done in dataannotation

View 5 Replies

Web Forms :: Treenode Attributes - How To Access

Mar 17, 2010

I couldn't find one that fit for the Treeview control. I have successfully binded my XmlDataSource to my Treeview control. Here is the XML

<ROOT rootName="Sales Literature Groups">
<saleslit_group slgrp_id="1" slgrp_name="PLCs" slgrp_loc="3A">
<sales_literature saleslit_id="1" saleslit_description="Literature #1" is_tube_mailer="0"/>
<sales_literature saleslit_id="2" saleslit_description="Literature #2" is_tube_mailer="0"/>
<sales_literature saleslit_id="3" saleslit_description="Literature #3" is_tube_mailer="1"/>
</saleslit_group>
</ROOT>

My question is whether it is possible or not to extract the "is_tube_mailer" field from the Treeview's Treenode. I attempted to cast the node.DataItem to an Xmlnode, however that only seemed to work in the TreeNodeDataBound event. I need to do this within a Button.Click event routine.

View 1 Replies

Access To Web.config Attributes (not AppSettings)?

Mar 23, 2011

given that I can add various addributes to the stock membership provider I assume I can do the same with my own provider implementation.

<add name="MyMembershipProvider" type="Portal.Infrastructure.MyMembershipProvider"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
[...] />

My question now: How do I access these values in the code? I understand that the ConfigurationManager can be used to access key value pairs in the appSettings section but this is different.

View 1 Replies

Forms Data Controls :: Access Querystring From Datagrid Cell?

Jan 12, 2010

I put a link on a datagrid that when loaded is attacehd to a url from the DB. Well when the Db holds nothing for that URl I need to be able to redirect to antoher page. Here is what I have so far. But It does not work, still using asp.net 1.1. Am i doing this correct or is there a different way.

<asp:TemplateColumn HeaderText="Fix Page">
<ItemTemplate>
<a href="<%# DataBinder.Eval(Container.DataItem, "strFilterPage") %>" target="_blank">Fix Page</a>
</ItemTemplate> [code].....

View 11 Replies

MVC :: Data Annotation W/ Linq To SQL Generated Classes?

May 14, 2010

Technically I have the Data Annoations working with Linq to SQL classes - the problem is when validation
passes. When UpdateModel() tries to do its thing i can an error:The model of type 'MyProject.Models.Employee' could not be updated.What i did was i created a partial class for Employee (that is generated by linq to sql), then stuck a Meta Data class on top of it for the validation

[Code]....

And in my master page i include

<script type="text/javascript" src="/Scripts/jquery.validate.min.js"></script>

View 9 Replies

Create Custom Data Annotation Validators?

Aug 5, 2010

Wanting to create custom data annotation validation. Are there any useful guides / samples on how to create them?

Firstly: StringLength with minimum and maximum length. I'm aware .NET 4 can do this, but want to do the same in .NET 3.5, if possible being able to define minimum length only (at least x chars), maximum length only (up to x chars), or both (between x and y chars).

Secondly: Validation using modulus arithmetic - if the number is a valid length, I wish to validate using the Modulus 11 algorithm (I have already implemented it in JavaScript, so I guess it would just be a simple porting?)

Update: Solved second problem, was just a case of copying over the JavaScript implementation and making a few tweaks, so don't need a solution for that.

View 1 Replies

MVC :: Access Html Helpers TextBox And Attributes?

Feb 5, 2010

i used Html Helpers TextBox like this

<%= Html.TextBoxFor(model => model.Password)%>

now have can i access to attributes

i need to enable=false that control.

View 3 Replies

Dynamically Access User Control Attributes?

Mar 18, 2010

Im trying to create a "user control menu" where links to a page's usercontrols are placed at the top of the page. This will allow me to put several usercontrols on a page and allow the user to jump to that section of the page without scrolling so much. In order to do this, I put each usercontrol in a folder (usercontrols) and gave each control a Description property (<%@ Control Language="C#" Description = "Vehicles" .... %>).

My question is how can I access this description dynamically? I want to use this description as the link in my menu. So far, I have a foreach on my page that looks in the ControlCollection for a control that is of the ASP.usercontrols type. If it is I would assume that I could access its attributes and grab that description property. How can I do this? (Im also open to a better way to achieve my "user control menu", but maybe thats another question.) Should I use ((System.Web.UI.UserControl)mydynamiccontrol).Attributes.Keys?

View 1 Replies

Forms Data Controls :: Datagrid Onprerender Possible To Access Value From Itemtemplate Label?

Apr 2, 2010

Is it possible to access the value of a label and want to tweak it before it to textbox which is in edititemtemplate column.

<ItemTemplate>
<asp:Label ID="lblUnitprice" Text='<%# FormatPrice(Container.DataItem("UnitPrice")) %>' Runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:Textbox runat="server" CssClass="TextBoxes" MaxLength="14" Columns="8" id="UnitPrice_edit" Text='<%# FormatPrice(Container.DataItem("UnitPrice")) %>' />
</EditItemTemplate>

Used onprerender a lot with dropdownlist boxes never used with textboxes.I have two currencies used in my application, want to format before i show to use.

View 3 Replies

C# - How To Restrict A Data Annotation's Usage To A Particular Property's Data Type

Mar 31, 2011

I have a validation attribute that inherits from ValidationAttribute. However, the particular usage of this attribute applies to lists only (IEnumerable really). How can I specify the usage of this property to only be used with items that inherit from IEnumerabe?

View 1 Replies

MVC Class Level Custom Data-annotation And ModelState Keys?

Apr 10, 2010

I have custom class level validation attribute, inheriting from ValidationAttribute, on my model.

How come it doesn't register a key in the ModelState when its IsValid is false? I can see the the error message in the ModelState.Values collection, but the ModelState.Keys collection only shows an empty string "". Can I provide a key for it - presumably this is because its not assigned to a property?

I wanna be able to use ModelState.Remove in my controller to remove this error upon a certain condition, but I have no Key!

View 1 Replies

MVC :: Data Annotation Validator REQUIRED On Client Side Not Work

Jun 6, 2010

Something is wrong in ASP.NET MVC 2 on client side validation. If I have form for create records in database and all fields are required, validation is triggered only then when I write something in field and delete it. If I go to field, stay this field empty and press Tab key validation isn't triggered.

Here somebody else write about the same problem: [URL]

View 1 Replies

C# - Access Gridview Attributes In Javascript - Change Font Size

Jan 19, 2010

I want to change the font size of my gridview in javascript because i am creating a printable version. How can I change the font size in javascript for the gridview?

View 2 Replies

MVC :: How To Display Model Level Custom Data Annotation Validation Error

Nov 30, 2010

I am a MVC newbie & am lost in various ways validation can be implemented in my application.

I created a custom model-level data annotation validator attribute, but am unable to display its error message in the view. Basically, I have let's say 5 properties in the Entity class Job (model-level custom attribute called UniqueKeywords defined on it):

1) LoginID: value comes in the URL

2) Title: Required property level attribute defined on it

3) CatID1, CatID2, CatID3 - 3 categoryIDs - these are dropdowns in the view with same list of keywords in all 3.

I want to mandate that the values picked by the user in all 3 category dropdowns should be different.

With reference to the code pasted below, here is the explanation of what happens:

When I submit the form without specifying a title or picking anything from any of the 3 category dropdowns, the validation occurs for the property level Required attribute as well as model level uniquekeywords attribute, but the error is displayed only next to the required field "Title". I can confirm that the custom validation also works by filling in some text in the Title field & then re-posting the form...this re-displays the view, but the error message "Category cannot be duplicated" is not displayed.

Only relevant code sections are pasted below:

My Entity class code:

[Code]....

View 10 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved