Search Results

Search found 200 results on 8 pages for 'dataannotations'.

Page 5/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • ASP.NET MVC 2 client side validation not working for Html.ValidationMessage()?

    - by JuniorDeveloper
    I'm trying to get a very simple client side validation example to work in ASP.NET MVC 2. I'm using data annotations to set a required property "Surname". When I use the Html.ValidationMessageFor(x = x.Surname) the correct client side validation script is written to the page. But when I use Html.ValidationMessage("Surname") the client side validation is not rendered out until after the page has been posted. Client side validation only starts working after a form post! I can see that the script is updated in the page after a form post. There appears to be a bug in Html.ValidationMessage()?

    Read the article

  • Automatically generate buddy classes from model in C#

    - by JohnnyO
    I use Linq to Sql (although this is equally applicable in Entity Framework) for my models, and I'm finding myself creating buddy classes for my models all the time. I find this time consuming and repetitive. Is there an easy way to automatically generate these buddy classes based on the models? Perhaps a visual studio macro? An example of a buddy class that I'd like to create: [MetadataType(typeof(PersonMetadata))] public partial class Person { } public class PersonMetadata { public object Id { get; set; } public object FirstName { get; set; } } Thanks in advance.

    Read the article

  • ASP.NET MVC does not add ModelError when invoking from unit test

    - by Tomas Lycken
    I have a model item public class EntryInputModel { ... [Required(ErrorMessage = "Description is required.", AllowEmptyStrings = false)] public virtual string Description { get; set; } } and a controller action public ActionResult Add([Bind(Exclude = "Id")] EntryInputModel newEntry) { if (ModelState.IsValid) { var entry = Mapper.Map<EntryInputModel, Entry>(newEntry); repository.Add(entry); unitOfWork.SaveChanges(); return RedirectToAction("Details", new { id = entry.Id }); } return RedirectToAction("Create"); } When I create an EntryInputModel in a unit test, set the Description property to null and pass it to the action method, I still get ModelState.IsValid == true, even though I have debugged and verified that newEntry.Description == null. Why doesn't this work?

    Read the article

  • Data Annotations on ViewModels or Domain Objects

    - by Ahmad
    Where would data annotations be more suitable: ViewModels or Domain Objects or Both I am struggling to decide where these will be more suited. I have not as yet fully utilized them but this question came to mind. From most of the examples I have seen, they are generally placed on Models and simply use the required attributes for validation using ModelState.IsValid. I have also seen another question on SO where the use of data annotations alone is not sufficient and advocate. Option 1 - I will still need to validate again in my service layer. ( I think that my service layer should be complete and this include validation, since its planned to be used elsewhere) Option 2 - How will I then get the benefits of the built in validation both client and server side. Option 3 - there will be a repetition of validation logic, however I was wondering if one could use a MetaData class approach that can be used for both ViewModels and Domain Objects. ( This is completely of the top of my head, so it may be nonsensical) I wonder if this question even makes sense. If not, can someone please help in understanding this better. Have I completely misunderstood the use of data annotations?

    Read the article

  • How to enforce unique-field validation in MVC

    - by xandy
    I am in the way building some MVC Application and I really love the Data Annotations support in MVC. The build in support is good enough to enforce simple validation checkup. I wonder, how to implement unique-field validation using custom data-annotation ? For example, I have a view model that need the user to register a new login name, is there way to check (using Model.IsValid) whether the name is not existed before calling the db submit?

    Read the article

  • Adding DataAnnontations to Generated Partial Classes

    - by Naz
    Hi I have a Subsonic3 Active Record generated partial User class which I've extended on with some methods in a separate partial class. I would like to know if it is possible to add Data Annotations to the member properties on one partial class where it's declared on the other Subsonic Generated one I tried this. public partial class User { [DataType(DataType.EmailAddress, ErrorMessage = "Please enter an email address")] public string Email { get; set; } ... } That examples gives the "Member is already defined" error. I think I might have seen an example a while ago of what I'm trying to do with Dynamic Data and Linq2Sql.

    Read the article

  • MVC 3 Remote Validation jQuery error on submit

    - by Richard Reddy
    I seem to have a weird issue with remote validation on my project. I am doing a simple validation check on an email field to ensure that it is unique. I've noticed that unless I put the cursor into the textbox and then remove it to trigger the validation at least once before submitting my form I will get a javascript error. e[h] is not a function jquery.min.js line 3 If I try to resubmit the form after the above error is returned everything works as expected. It's almost like the form tried to submit before waiting for the validation to return or something. Am I required to silently fire off a remote validation request on submit before submitting my form? Below is a snapshot of the code I'm using: (I've also tried GET instead of POST but I get the same result). As mentioned above, the code works fine but the form returns a jquery error unless the validation is triggered at least once. Model: public class RegisterModel { [Required] [Remote("DoesUserNameExist", "Account", HttpMethod = "POST", ErrorMessage = "User name taken.")] [Display(Name = "User name")] public string UserName { get; set; } [Required] [Display(Name = "Firstname")] public string Firstname { get; set; } [Display(Name = "Surname")] public string Surname { get; set; } [Required] [Remote("DoesEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "Email taken.", AdditionalFields = "UserName")] [Display(Name = "Email address")] public string Email { get; set; } [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)] [DataType(DataType.Password)] [Display(Name = "Confirm password")] public string ConfirmPassword { get; set; } [Display(Name = "Approved?")] public bool IsApproved { get; set; } } public class UserRoleModel { [Display(Name = "Assign Roles")] public IEnumerable<RoleViewModel> AllRoles { get; set; } public RegisterModel RegisterUser { get; set; } } Controller: // POST: /Account/DoesEmailExist // passing in username so that I can ignore the same email address for the same user on edit page [HttpPost] public JsonResult DoesEmailExist([Bind(Prefix = "RegisterUser.Email")]string Email, [Bind(Prefix = "RegisterUser.UserName")]string UserName) { var user = Membership.GetUserNameByEmail(Email); if (!String.IsNullOrEmpty(UserName)) { if (user == UserName) return Json(true); } return Json(user == null); } View: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js" type="text/javascript"></script> <script type="text/javascript" src="/Content/web/js/jquery.unobtrusive-ajax.min.js"></script> <script type="text/javascript" src="/Content/web/js/jquery.validate.min.js"></script> <script type="text/javascript" src="/Content/web/js/jquery.validate.unobtrusive.min.js"></script> ...... @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="titleh"> <h3>Edit a user account</h3> </div> <div class="body"> @Html.HiddenFor(model => model.RegisterUser.UserName) @Html.Partial("_CreateOrEdit", Model) <div class="st-form-line"> <span class="st-labeltext">@Html.LabelFor(model => model.RegisterUser.IsApproved)</span> @Html.RadioButtonFor(model => model.RegisterUser.IsApproved, true, new { @class = "uniform" }) Active @Html.RadioButtonFor(model => model.RegisterUser.IsApproved, false, new { @class = "uniform" }) Disabled <div class="clear"></div> </div> <div class="button-box"> <input type="submit" name="submit" value="Save" class="st-button"/> @Html.ActionLink("Back to List", "Index", null, new { @class = "st-clear" }) </div> </div> } CreateEdit Partial View @model Project.Domain.Entities.UserRoleModel <div class="st-form-line"> <span class="st-labeltext">@Html.LabelFor(m => m.RegisterUser.Firstname)</span> @Html.TextBoxFor(m => m.RegisterUser.Firstname, new { @class = "st-forminput", @style = "width:300px" }) @Html.ValidationMessageFor(m => m.RegisterUser.Firstname) <div class="clear"></div> </div> <div class="st-form-line"> <span class="st-labeltext">@Html.LabelFor(m => m.RegisterUser.Surname)</span> @Html.TextBoxFor(m => m.RegisterUser.Surname, new { @class = "st-forminput", @style = "width:300px" }) @Html.ValidationMessageFor(m => m.RegisterUser.Surname) <div class="clear"></div> </div> <div class="st-form-line"> <span class="st-labeltext">@Html.LabelFor(m => m.RegisterUser.Email)</span> @Html.TextBoxFor(m => m.RegisterUser.Email, new { @class = "st-forminput", @style = "width:300px" }) @Html.ValidationMessageFor(m => m.RegisterUser.Email) <div class="clear"></div> </div> Thanks, Rich

    Read the article

  • Asp MVC - "The Id field is required" validation message on Create; Id not set to [Required]

    - by burnt_hand
    This is happening when I try to create the entity using a Create style action in Asp.Net MVC 2. The POCO has the following properties: public int Id {get;set;} [Required] public string Message {get; set} On the creation of the entity, the Id is set automatically, so there is no need for it on the Create action. The ModelState says that "The Id field is required", but I haven't set that to be so. Is there something automatic going on here? EDIT - Reason Revealed The reason for the issue is answered by Brad Wilson via Paul Speranza in one of the comments below where he says (cheers Paul): You're providing a value for ID, you just didn't know you were. It's in the route data of the default route ("{controller}/{action}/{id}"), and its default value is the empty string, which isn't valid for an int. Use the [Bind] attribute on your action parameter to exclude ID. My default route was: new { controller = "Customer", action = "Edit", id = " " } // Parameter defaults EDIT - Update Model technique I actually changed the way I did this again by using TryUpdateModel and the exclude parameter array asscoiated with that. [HttpPost] public ActionResult Add(Venue collection) { Venue venue = new Venue(); if (TryUpdateModel(venue, null, null, new[] { "Id" })) { _service.Add(venue); return RedirectToAction("Index", "Manage"); } return View(collection); }

    Read the article

  • where should I put the EF entity and data annotations in asp.net mvc + entity framework project

    - by giddy
    So I have a DataEntity class generated by EntityFramework4 for my sqlexpress08 database. This data context is exposed via a WCF Data Service/Odata to silverlight and win forms clients. Should the data entities + edmx file (generated by EF4) go in a separate class library? The problem here then is I would specify data annotations for a few entities and then some of them would require specific MVC attributes (like CompareAttribute) so the class library would also reference mvc dlls. There also happen to be entity users which will be encapsulated or wrapped into an IIdentity in the website. So its pretty tied to the mvc website. Or Should it maybe go in a Base folder in the mvc project itself? Mostly the website is data driven around the database, like approve users, change global settings etc. The real business happens in the silverlight and win forms apps. Im using mvc3 rc2 with Razor. Thanks

    Read the article

  • Add LINQ Auto-Generated Value Marker [Column(IsDbGenerated=true)] in Buddy Class

    - by Alex
    Hello, is it possible to decorate a field of a LINQ generated class with [Column(IsDbGenerated=true)] using a buddy class (which is linked to the LINQ class via [MetadataType(typeof(BuddyMetadata))]) ? My goal is to be able to clear and repopulate the LINQ ORM designer without having to set the "Auto Generate Value" property manually every time to re-establish the fact that certain columns are autogenerated. Thanks!

    Read the article

  • Custom model validation of dependent properties using Data Annotations

    - by Darin Dimitrov
    Since now I've used the excellent FluentValidation library to validate my model classes. In web applications I use it in conjunction with the jquery.validate plugin to perform client side validation as well. One drawback is that much of the validation logic is repeated on the client side and is no longer centralized at a single place. For this reason I'm looking for an alternative. There are many examples out there showing the usage of data annotations to perform model validation. It looks very promising. One thing I couldn't find out is how to validate a property that depends on another property value. Let's take for example the following model: public class Event { [Required] public DateTime? StartDate { get; set; } [Required] public DateTime? EndDate { get; set; } } I would like to ensure that EndDate is greater than StartDate. I could write a custom validation attribute extending ValidationAttribute in order to perform custom validation logic. Unfortunately I couldn't find a way to obtain the model instance: public class CustomValidationAttribute : ValidationAttribute { public override bool IsValid(object value) { // value represents the property value on which this attribute is applied // but how to obtain the object instance to which this property belongs? return true; } } I found that the CustomValidationAttribute seems to do the job because it has this ValidationContext property that contains the object instance being validated. Unfortunately this attribute has been added only in .NET 4.0. So my question is: can I achieve the same functionality in .NET 3.5 SP1? UPDATE: It seems that FluentValidation already supports clientside validation and metadata in ASP.NET MVC 2. Still it would be good to know though if data annotations could be used to validate dependent properties.

    Read the article

  • MVC4 - how to vaildate a drop down list?

    - by Grant Roy
    I have a .Net MVC4 model / view with a number of [Required] fields, one of which is selected via a drop down list, "Content_CreatedBy" [the first code block below]. Client side validation fires on all fields except the DDL [although server side validation does not allow no entry in DDL]. I have tried validating on the DDL text as well its numeric value but niether fire on the client side. Can anyone see what I am doing wrong? Thanks Model [Required] [Display(Name = "Author")] [ForeignKey("ContentContrib")] [Range(1, 99, ErrorMessage = "Author field is required.")] public virtual int Content_CreatedBy { get; set; } [Required] [Display(Name = "Date")] public virtual DateTime Content_CreatedDate { get; set; } [Required] [DataType(DataType.MultilineText)] [Display(Name = "Source / Notes ")] [StringLength(10, MinimumLength = 3)] public virtual string Content_Sources { get; set; } [Required] [Display(Name = "Keywords")] [StringLength(50, MinimumLength = 3)] public virtual string Content_KeyWords { get; set; } VIEW <div class="editor-label"> @Html.LabelFor(model => model.Content_CreatedBy, new { @class="whitelabel"}) </div> <div class="editor-field"> @Html.DropDownList("Content_CreatedBy", String.Empty) @Html.EditorFor(model => model.Content_CreatedBy) @Html.ValidationMessageFor(model => model.Content_CreatedBy) </div>

    Read the article

  • MVC2 Data Annotation Buddy Classes Doesn't seem to work when Classes and EOM Model is in separate Project

    - by Danish Ali
    Dear All Iam new to MVC2 and having a little problem with implementing validation via buddy classes. Iam using Repository pattern with dependency injection. My Entity Object Model is in Data Layer Project and Buddy Classes are in Business Layer project and MVC 2 Project as a separate Presentation Layer Project. Can any one help me out with implementing Buddy Classes in this Architecture. Thanks and Regards Dani

    Read the article

  • How to dynamically set validation messages on properties with a class validation attribute

    - by Dan
    I'm writing Validation attribute that sits on the class but inspects the properties of the class. I want it to set a validation message on each of the properties it finds to be invalid. How do I do this? This is what I have got so far: [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class LinkedFieldValidationAttribute : ValidationAttribute { private readonly string[] _properiesToValidate; public LinkedFieldValidationAttribute(params string[] properiesToValidate) { _properiesToValidate = properiesToValidate; } public override bool IsValid(object value) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); foreach (var propertyName in _properiesToValidate) { var propertyValue = properties.Find(propertyName, false).GetValue(value); //if value is invalid add message from base } //return validity } }

    Read the article

  • Range validation not working properly in MVC3

    - by Colin Desmond
    I am generating data validation javascript in an Asp.Net MVC 3 application with the following code [DisplayName("Latitude Degrees")] [Range(0, 90, ErrorMessage = "Latitude degrees must be between {1} and {2}")] public Int32? LatitudeDegrees { get; set; } on a view model. When it was MVC2 this worked just fine, if I entered a value outside of 0-90 in the textbox I got the validation warnings. Since I moved the application to MVC 3, whenever I put any value into the texbox, legal or illegal I get the validation error appear next to it. I have EnableClientValidation set to true and UseUnobtrusiveJavascript is off (nothing in web.config or the views to turn it on).

    Read the article

  • Range annotation between nothing and 100?

    - by aticatac
    Hi I have a [Range] annotation that looks like this: [Range(0, 100)] public int AvailabilityGoal { get; set; } It works as it should, I can only enter values between 0 and 100 but I also want the input box to be optional, the user shouldn't get an validation error if the input box is empty. If the user leaves it empty it should make AvailabilityGoal = 0 but I don't want to force the user to enter a zero. I tried this but it (obviously) didn't work: [Range(typeof(int?), null, "100")] Is it possible to solve this with Data Annotations or in some other way? Thanks in advance. Bobby

    Read the article

  • Asp MVC - "The Id field is required" validation message on Create; Id not set to [Required]

    - by Dann
    This is happening when I try to create the entity using a Create style action in Asp.Net MVC 2. The POCO has the following properties: public int Id {get;set;} [Required] public string Message {get; set} On the creation of the entity, the Id is set automatically, so there is no need for it on the Create action. The ModelState says that "The Id field is required", but I haven't set that to be so. Is there something automatic going on here? EDIT - Reason Revealed The reason for the issue is answered by Brad Wilson via Paul Speranza in one of the comments below where he says (cheers Paul): You're providing a value for ID, you just didn't know you were. It's in the route data of the default route ("{controller}/{action}/{id}"), and its default value is the empty string, which isn't valid for an int. Use the [Bind] attribute on your action parameter to exclude ID. My default route was: new { controller = "Customer", action = "Edit", id = " " } // Parameter defaults EDIT - Update Model technique I actually changed the way I did this again by using TryUpdateModel and the exclude parameter array asscoiated with that. [HttpPost] public ActionResult Add(Venue collection) { Venue venue = new Venue(); if (TryUpdateModel(venue, null, null, new[] { "Id" })) { _service.Add(venue); return RedirectToAction("Index", "Manage"); } return View(collection); }

    Read the article

  • How can I support conditional validation of model properties

    - by Jeff
    I currently have a form that I am building that needs to support two different versions. Each version might use a different subset of form fields. I have to do this to support two different clients, but I don't want to have entirely different controller actions for both. So, I am trying to come up with a way to use a strongly typed model with validation attributes but have some of these attributes be conditional. Some approaches I can think of is similar to steve sanderson's partial validation approach. Where I would clear the model errors in a filter OnActionExecuting based on which version of the form was active. The other approach I was thinking of would to break the model up into pieces using something like class FormModel { public Form1 Form1Model {get; set;} public Form2 FormModel {get; set;} } and then we would validate appropriately depending on

    Read the article

  • asp.net mvc dataannotation different table

    - by mazhar kaunain baig
    i have a lang table which is as a foreign key in the link table , The link can be in 3 languages meaning there will be 3 rows in the link table everytime i enter the record. i am using jquery tabs to enter the records in 3 languages . ok so what architecture i should follow for validation with datannotation attributes. i am using link to sql with 2010 vs. i will be creating link class with MetadataType so how will i handle for eg link name attribute 3 times.

    Read the article

  • Data-annotation getting errormessage out database

    - by Masna
    Hello, With asp.net mvc you can use the annotation [Required (errormessage="This is required")] How can I create something like this: [Required (errormessage="ERRORXX")] So I can look up in a database what this ERRORXX is and display it on my form. Now my form displays ERRORXX. How can I create something that solves my problem? Thx!

    Read the article

  • How do I get my custom requiredif attribute to prevent other attributes from firing

    - by user1757804
    I'm working on an MVC application. I've decorated a property with EqualTo found here: http://dataannotationsextensions.org/EqualTo/Create As well as a custom RequiredIf attribute as suggested here: http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx My issue is that even when the field is supposed to be required and isn't the EqualTo logic is firing. So I get error messages saying the field is required but also that the field doesn't match. If I replace the Requiredif with a regular Required only the Required message will show. What I'm trying to figure out is how the EqualTo logic is prevented when combined with the Required attribute but not prevented when combined with my custom RequiredIf. Any suggestions would be most appreciated, I've been racking my brain most of the day trying to figure out the mvc internals around Required.

    Read the article

  • MVC Validator.TryValidateObject does not validate custom atrribute, validateAllProperties = true

    - by nealsu
    When calling Validator.TryValidateObject with validateAllProperties = true my custom validation attribute does not get triggered. The ValidationResult does not contain an entry for my erroneous property value. Below is the model, attribute and code used to test this. //Model public class Model { [AmountGreaterThanZero] public int? Amount { get; set; } } //Attribute public sealed class AmountGreaterThanZero: ValidationAttribute { private const string errorMessage = "Amount should be greater than zero."; public AmountGreaterThanZero() : base(errorMessage) { } public override string FormatErrorMessage(string name) { return errorMessage; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { if ((int)value <= 0) { var message = FormatErrorMessage(validationContext.DisplayName); return new ValidationResult(message); } } return null; } } //Validation Code var container = new Container(); container.ModelList = new List<Model>() { new Model() { Amount = -5 } }; var validationContext = new ValidationContext(container, null, null); var validationResults = new List<ValidationResult>(); var modelIsValid = Validator.TryValidateObject(container, validationContext, validationResults, true); Note: That the validation works fine and ValidationResult returns with correct error message if I use the TryValidateProperty method.

    Read the article

  • Field annotated multiple times by the same attribute

    - by Jaroslaw Waliszko
    For my ASP.NET MVC application I've created custom validation attribute, and indicated that more than one instance of it can be specified for a single field or property: [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class SomeAttribute: ValidationAttribute I've created validator for such an attribute: public class SomeValidator : DataAnnotationsModelValidator<SomeAttribute> and wire up this in the Application_Start of Global.asax DataAnnotationsModelValidatorProvider.RegisterAdapter( typeof (SomeAttribute), typeof (SomeValidator)); Finally, if I use my attribute in the desired way: [SomeAttribute(...)] //first [SomeAttribute(...)] //second public string SomeField { get; set; } when validation is executed by the framework, only first attribute instance is invoked. Second one seems to be dead. I've noticed that during each request only single validator instance is created (for the first annotation). How to solve this problem and fire all attributes?

    Read the article

  • Is it possible to use Data Annotations to validate parameters passed to an Action method of a Contro

    - by dannie.f
    I am using Data Annotations to validate my Model in ASP.NET MVC. This works well for action methods that has complex parameters e.g, public class Params { [Required] string Param1 {get; set;} [StringLength(50)] string Param2 {get; set;} } ActionResult MyAction(Params params) { If(ModeState.IsValid) { // Do Something } } What if I want to pass a single string to an Action Method (like below). Is there a way to use Data Annotations or will I have to wrap the string into a class? ActionResult MyAction(string param1, string param2) { If(ModeState.IsValid) { // Do Something } }

    Read the article

  • DisplayFor ignores metadata

    - by Juvaly
    For my Contact class, the property EmailAddress is marked with the [DataType(DataType.EmailAddress)] attribute. In my view, using Html.Display("EmailAddress") and Html.DisplayFor(c => c.EmailAddress) yields different results. The former outputs a mailto: link, which is the expected behavior, while the latter simply outputs the email address as plain text. My question is why the different behavior, I expected these two methods to have the same output.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >