MVC :: Authorize Role Validation At Model Level?

Jan 22, 2010

I am not being able to use User Role at model level. I need this to grant control to each repository's method individualy.

This works fine at the objectController, at the controller level:


But at the objectRepository, model level, the following compiles but is ignored:


ASP.NET MVC doesn't allow this? Is there any way arround?

View 14 Replies

Similar Messages:

MVC :: Level Model Members - Add Validation Support To TextRef Items

Mar 31, 2011

i'm working on a MVC3 webapp and my Model consist of many classes that use a custom type (TextRef) for textual properties. for example my Product entity looks like :


TextRef :


so in my views i'm using :


how could i add validation support to TextRef items ? for example making Product.Title required

View 5 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:


View 10 Replies

Web Forms :: Menu - Role Security Not Working On Second Level Of Sitemap

Sep 24, 2010

I have role assignments on both the first and second level of my menus within my sitemap file. The first level works fine, and I only see items assigned to my role. But roles assignments seem to have no effect on the second level. It seems like if you have access to the first level, you have access to everything on the second level. Is this correct?

From my sitemap (either a SalesRep or an Administrator can see everything underneath):
<siteMapNode title="Administration" roles="SalesRep,Administrator" description="Admin" >
<siteMapNode title="CompanyMaintenance" roles="SalesRep" url="~/Admin/CompanyManagement.aspx" />
<siteMapNode title="Initialize Roles" roles="Administrator" url="~/Admin/Roles.aspx"/>

View 3 Replies

MVC :: Access Model Validation Inside Custom Model Binder?

Sep 1, 2010

Is it possible, inside a Custom Model Binder, to fire "something" that "says" the value is invalid so it gets handled by validation part?

Basically, I am getting an exception when the value for the property is invalid.

View 1 Replies

MVC :: ValidationSummary / Only Displays Model-level Errors?

May 18, 2010

If I pass in true to the ValidationSummary() helper so that it only displays model-level errors, how can I get the summary to display custom errors I add to ModelState?For instance, here is what I am after. I want my data annotation errors to display next to the textbox's using the ValidationMessage helper, but in my business layer I may throw an exception that I want to display in the validation summary.

View 1 Replies

MVC :: Dependency Injection / The Role Of A 'Model'?

May 27, 2010

My general understanding of the MVC pattern is that the model is reponsible for persisting itself. Though I also see other opionions that models should be dumb data objects and that controllers should persist them via a data access layer.

Per "Many applications use a persistent storage mechanism such as a database to store data. MVC does not specifically mention the data access layer because it is understood to be underneath or encapsulated by the model." Though it does also mention "Models are not data access objects."

Per, "Models. Model objects are the parts of the application that implement the logic for the applications data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in SQL Server."

First, am I misguided in believing that models should persist themselves? Or, is this just a matter of opinion?

Second, if I follow the pattern where controllers manage the persistence of the model, I find it fairly easy to use dependency injection to inject a data access component into my controller using a custom controller factory (implementing the IControllerFactory
interface). If I follow the pattern where my model saves itself, I'd want to inject my data access component into the model. Is there a way to provide a custom factory for models? Otherwise, I don't think using DI with models is possible.

View 5 Replies

ADO.NET :: Entity Model Insert Many To Many - Add User To Role?

Dec 27, 2010

Im using an Entity data model & Linq for the first time. I have also setup a basic membership system.

Im just not sure how to add a user to a role over many to many relationship.

Right now I have the user/userid selected from a dropdown and also have a button to process the add.

View 1 Replies

MVC - Factor Repository Interfaces Based On Multi - Level Object Model?

Feb 15, 2011

I've got a multi level dependency chain in my object model: An organization has the following children relationships:


This is just a glimpse at the object model, but it's focused on the complexity of the relationships and lists. What I can't really get is what's the best way to factor my repository interfaces, given the requirements to do a unit of work. For example, to create a game, you'll need a venuedate and two participants. Does that mean the GamesController should require an IGameRepository, an IVenueDateRepository, and an IParticipant repository? Should they be rolled into one repository?

Also, what about in the consumption cases? For example, to display a signle team's schedule, you'll need all of the Participants for that Team, all of the Games for that participant, and all of the GameSegments for the participant. If those are factored into individual repositories I can't see how you can do efficient queries. Does that mean you have Repositories specifically focused on different cases? for example:

public interface IScheduleRepository {
public ICollection<Game> GetScheduleForTeam(Team team);
// More consumption methods
public class ScheduleRepositry : IScheduleRepository {
public ScheduleRepository (ModelContext context) {
// Do stuff with context
public ICollection<Game> GetScheduleForTeam(Team team) {
return (
from p in context.Participants
where ((p.Game.VenueDate != null) &&
(p.TeamId == team.Id))
orderby p.Game.VenueDate.StartTime
select p.Game).ToList();
// more consumption methods
public interface IGameRepository {
public void AddGame(Game game);
// More crud methods
// Not showing games repository
public class GamesController : Controller {
public GamesController (IGameRepository gamesRepo,
IVenueDateRepository venueDateRepo,
IParticipantRepository participantRepo) {
// do stuff with repos here
public ActionResult AddGame(Game game) {
// Skipping validation logic
// this?
VenueDate = venueDateRepo.Add(game.VenueDate);
foreach (Participant p in Game.Participants)
Game = gamesRepo.AddGame(game);
// or this?
// how would the game repo know to persist
// the children elements? is that tight coupling?
Game = gamesRepo.AddGame(game);
// more consumption methods

My question is I don't yet understand to what degree factoring your repositories make sense based on a connected object model. I'd love to get some advice here.

View 1 Replies

MVC :: Validation Of Model In Side Model

Oct 12, 2010

I have recently started working on ASP.NET with MVC 2 framework, and I am facing following difficulty in validating my data,


In my application the view (ASPX) is divided into tabs (jQuery) and each tab's content is ViewUserControl (ASCX). The main model for the view has collection of sub models for individual tabs. I use RenderPartial method to render view user control.


And the user control (Tab1.ascx) refers the specific model for it,


Now if in my Tab1Model if I put following validation


In the controller ModelState.IsValid is always indicates TRUE. How do I override the validation behavior such that it as well looks the items in the collection member (which holds sub models) as well.

<%= Html.ValidationMessage("FirstName") %>

View 1 Replies

User Is In Role "admin" But (Authorize (Roles="admin")) Won't Authenticate

Mar 15, 2011

I found a great answer on SO describing how to set up custom user roles, and I've done the same in my project. So in my Login service I have:

public ActionResult Login() {
// password authentication stuff omitted here
var roles = GetRoles(user.Type); // returns a string e.g. "admin,user"
var authTicket = new FormsAuthenticationTicket(
DateTime.Now.AddMinutes(20), // expiry
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
return new XmlResult(xmlDoc); // don't worry so much about this - returns XML as ActionResult
And in Global.asax.cs, I have (copied verbatim from the other answer):
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
var authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null) {
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var roles = authTicket.UserData.Split(new Char[] { ',' });
var userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
Context.User = userPrincipal;
Then, in my ServicesController class, I have:
[Authorize(Roles = "admin")]
public ActionResult DoAdminStuff() {

I login as a user with the "admin" role, and that works. Then I call /services/doadminstuff - and I get access denied, even though when I put a breakpoint in Global.asax.cs, I can see that my roles do include "admin". If I comment out the first Authorize attribute (with roles) and just use a plain vanilla Authorize, then I can access the service.

View 1 Replies

Custom Role Provider - Additional Fields - Represent Multi - Layered Security Model

Apr 4, 2011

There are multiple roles. (Role A, Role B etc) There are multiple input/output fields. (Field A, Field B etc) There are multiple permission levels controlling access to each field. (Read, Direct Edit, Edit With Approval, None) Each role has its own permissions to fields. (Role A has Read Permission to Field A; Role B has Direct Edit permission to Field A etc) Every role can be assigned to users and they are assigned by Geographic information. (User A is assigned to Role A for Continent: Europe - Country: Germany; User B is assigned to Role A for Continent: Europe - Country: France; User A is assigned to Role B for Continent: Europe - Country: France etc) Users can have multiple roles User identity is coming from Windows Authentication.

is it possible to represent this type of kind of multi-layered security model using ASP.NET internal membership/role providers? If so, what should my starting point be? Creating only custom role provider with custom methods and fields be enough?

View 3 Replies

MVC :: Model Validation For File Upload?

Aug 17, 2010

My MVC 2 app includes a simple file upload within in a strongly typed view and I am trying to figure out how to apply model validation to the file name. Is this possible? Is there better way to do file upload within an MVC app?

The salient parts of the (prototype) controller code are:


The Create view code was generated with VS2010 and then modified to support file upload and client side validation:


View 3 Replies

Localize Default Model Validation In Mvc 2?

Jul 1, 2010

[DisplayName("my date")]
public DateTime? DateReg { get; set; }

so if the user is going to pass in an invalid datetime value he will get this message "The value '02.07.201022' is not valid for my date."

View 1 Replies

MVC :: Validation For String Array In Model?

Mar 25, 2011

I am using an array to keep track what checkboxes a user has clicked.


However, validation doesn't seem to work for this field. This is how I am rendering it in the view:




View 3 Replies

MVC :: Validation With Model As Property To ViewModel?

Jan 11, 2011

I have a viewmodel with a property of a model class type. I set some properties in the model class to be able to show it to the user but then when I make a post, the model gets validated. How to overcome this? I don't want to enforce the DataAnnotations contraint in this case....

public class TheViewModel
TheModel TheModel { get; set;}

View 1 Replies

C# - Model Validation With ViewModel Don't Works?

Dec 9, 2010

I use viewModels to communicate between my controller and my view. To get model validation, i use a partial class like this :

public partial class Evaluation
public class EvaluationValidation
[DisplayName("Title of evaluation")]


View 1 Replies

MVC :: Multiple Model Validation In Same View?

Jul 10, 2010

I have a Order view with 2 user controls in it.

The first user control in the view is just to validate the customer and get some more details about the customer. This control is having one text box (customer name) with the button. When the user clicks the button it should validate the customer name in the client side using data annotations of customer model. if validation success then it should use some bussiness logic to verify the customer and show the customer details on the form.

The 2nd user control in the view is to get the address of the customer by searching for the house no and the postcode. This control is having 2 text box with the button.

The first user control is based on the strongly typed customer entity

The 2nd user control is bsed on the strongly typed address entity

The view with both the user control is based on the strongly typed order entity.

The issue here is with the validation. I have the validation summary in the view and client sider validation is enabled. When i click the search button on the first user control the client validation starts and throws validation error messages because when i search for the customer at that point of time i will not have values to may of the customer related fields in the order view.

The same thing happen when i click the search button on the 2nd view. It will throw client side validation for other fields.

What i want to achive is that when the user click the search button on the user control 1 then the validation should happen only to the customer name field (both in client and server).

When the user click the search button on the 2 nd user control the the validation should happen only for houseno and the postcode both in client and the server.

When the user clicks the save button on the order view all the fields in the form even the controls usere input fields should get validated. How to achive this in mvc?

View 4 Replies

MVC :: Controlling Order Of Model Validation?

Jul 6, 2010

With my model, I have one view model using another as its base. In my case, BaseUserModel is inherited by CreateUserModel, in order to share common properties such as Username and Password. My CreateUserModel adds to that by having ConfirmPassword, Email, SecurityQuestion, etc.

My problem is, when using the ValidationSummary() Html helper, the validation is obviously in order of the properties in my model. Basically, because of the inheritance I have going on here, the errors are not in the correct order.

Is it possible to control when or how these validation rules are added to the list? The only attribute I'm using is Required.

View 2 Replies

MVC :: How To Use Of Validation With Data Annotations In Model Classes

Dec 12, 2010

I make use of validation with data annotations in my model classes. How do I make sure this annotations are not violated when I validate data in my business layer, before sending it to the DAL? I guess I don't want to define the validation rules in two places (model classes and in my BLL-classes)?

View 6 Replies

MVC :: Model Validation Passes In Firefox And It Fails In IE

Feb 14, 2010

I am uploading a JPEG image in an ASP.NET MVC web site.

The model validation fails in IE, but passes in Firefox, when I try to check the mime type of the

So I debuged it and I found that when using Firefox the Mime type is "image/jpeg" as expected.

When using IE8 the mime type is "image/pjpeg".

Don't say that Microsoft invented a new Mime Type of JPeg images?

View 3 Replies

MVC :: Changing Model Validation At Runtime Programmatically

Jul 9, 2010

I'm starting with MVC 2. Very cool.I have been reading about the data annotations validation attributes that can be set on the view model properties.It's cool but I have a scenario where I need to determine at runtime whether one of the property is required or not.How can I achieve this ? I want to have client side validation enabled too.

View 6 Replies

MVC :: Can't Get Model Client Validation Messages Localized?

May 23, 2010

i am currently working on an mvc (.net 3.5 sp1) web app, that uses data annotations and client side validation. I would like to have localization enabled, thus i have implemented a localization mechanism for enabling site visitors select the locale they prefer, by overriding the Execute() controller action and setting the CurrentCulture appropriately (i get the culture to change to from the URL route parameters).

I tried implementing my model validation messages localization with no success. What i did was adding two resource files undeer my model App_LocalResoorces folder (one for my locale greek language Validation.el.resx and one for the default english language Validation.el.resx) and set the appropriate file properties ("Access Modifier" to "Public", "Build Action" to "Embedded Resource","CustomTool" to "PublicResXFileCodeGenerator" and "Custom Tool Namespace" to "ModelLocalRes". Then i added a RequiredFieldPrompt" name-value to both the resource files.

Then i tried modify the required validation attribute on my model's name metadata like this:


The problem is that i cannot get the localization working, since the error message gets displayed always for the english default locale, no matter the locale selected from the site visitor.

View 11 Replies

MVC 2 Model Validation Messages - Turn Off / Customized?

Oct 19, 2010

i have a view model with a property like this one :

[RegularExpression(@"^d+$", ErrorMessageResourceType = typeof(Resources.Validation), ErrorMessageResourceName = "NumberValidationMsg" )]
public int? Number {get; set;}

NumberValidationMsg resource is set to "Only numbers allowed !".

but when I try to enter something like 'test' into Number field on form, ModelState displays the ErrorMessage with content similar to :

"The value 'test' is not valid for Number."

can this message be turned off, customized? (or maybe the best solution would be just to replace int? with string)

View 1 Replies

MVC :: Model Validation Of Excel Imported Data?

Jan 23, 2011

I use FileHelpers to import data from excel sheet to classes and then put it in MSSQL. Can somebody tell me if there is there a way to do model validation data imported from excel files?

View 6 Replies

Copyrights 2005-15, All rights reserved