Validating Uniqueness With Data Annotations In Mvc

Oct 7, 2010

I have various questions about validation using data annotations. I am using the following setup

asp.net mvc 2
entity framework 4
data annotations

Basically, I'm trying to get unique validation working and i'm a little confused. My models are as follows:

public class Buyer
{
public int Id { get; set; }
[Required(ErrorMessage = "The email is required")]
public string Email { get; set; }
[Required(ErrorMessage= "The name is required")]
public string Name { get; set; }
}
public class Seller
{
public int Id { get; set; }
[Required(ErrorMessage = "The email is required")]
public string Email { get; set; }
[Required(ErrorMessage= "The name is required")]
public string Name { get; set; }
}...............................................

View 1 Replies


Similar Messages:

MVC :: Re Validating Model Data When Using Data Annotations?

Apr 18, 2010

I am using Data Annotations in ASP.NET MVC2 for data validation.There are cases where Model is invalid in Control Action method, by the time I received it. So I add defaults [where data is not present in cetain scenarios, for valid reasons. Other times it is error].All I want to do at this point is, because I updated the model, I want to re-validate model - so that it re-applies all validation again as per data annotations.

If I call Controller.ValidateModel method, I am getting exception saying, it cannot take the model object or type is not correct.If I don't re-validate, my Model.IsValid is false -even though I set up defaults.I am wondering if there a way I can call to re-validate model, from in-side a controller action?

View 5 Replies

MVC :: Routes Uniqueness And SEO - Using Id And Name As Parameters In The Actions?

Feb 2, 2010

I am using the Default Route as follows:

routes.MapRouteLower("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });

However, beacause of SEO I would also like to filter not by id but by name. Something like: Product/Show/RedBall instead of Product/Show/2345 And if RedBall is not unique what would be a good approach to do this? Maybe start using the following: Product/Show/2345/RedBall Using Id and Name as parameters in the actions?

View 2 Replies

MVC :: Using Data Annotations For Display Name?

Mar 23, 2010

I am using VS2010 RC and i created a buddy class. My problem is that i cant seem to see the option to change the Display name of a column.i only see "displaycolumn" and "displayformat".

View 7 Replies

Bypass Data Annotations Validation On MVC 2?

Aug 4, 2010

I would like to know if it's possible to bypass the validation of one property which is using Data Annotations. Since I use the model across multiple pages, there's a check I need in some, but not in others, so I would like it to be ignored.

View 2 Replies

MVC :: Default Resource For Data Annotations?

Jul 27, 2010

There's a way to set the default resource to the data annotations validations?I don't wanna make something like this:

[Code]....

I would like something like this:Global.asax

[Code]....

View 3 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 :: Defining Validation Rules With Data Annotations?

Sep 24, 2010

Defined RegisterModel class - with some validation rules for creating new users, and this works fine.

Then I get this class, strip few properties and wanted to reuse it as UserInfo_Form_Model, for editing user properites.

No changes, just deleted few items, renamed and reused in strongly typed View for editing.

And result of validation is: -

[DisplayName("Name")] works fine, showing correct

[StringLength(20, ErrorMessage = "xxxx...")] - not working, no message showed when suppose to be one

[Required(ErrorMessage = "xxxx.")] - not working, not showing messages when delete required values?

but (ModelState.IsValid) is false when I checked it in controller (it had to be because required value is missing)?

Is it this only partially correct and how this can be?

Well this is a bit frustrating because it cant be simpler than this and I cant make this simple code reuse.

View 3 Replies

Data Annotations For Validation At Least One Required Field?

Apr 26, 2010

If I have a search object with a list of fields, can I, using the System.ComponentModel.DataAnnotations namespace, set it up to validate that at least one of the fields in the search is not null or empty? i.e All the fields are optional but at least one should always be entered.

View 2 Replies

C# - Assign Format Of DateTime With Data Annotations?

Mar 9, 2011

I have this attribute in my view model:

[DataType(DataType.DateTime)]
public DateTime? StartDate { get; set; }

If I want to display the date, or populate a textbox with the date, I have these:

<%: Model.StartDate %>
<%: Html.TextBoxFor(m => m.StartDate) %>

Whenever the date is displayed, it's displayed like: 01/01/2011 12:00:00 AM

But I'd like to only display 01/01/2011

Is there a way to apply a display format with data annotations? I don't want to have to go to every instance where I display a date, and add some code to format it.

View 1 Replies

JQuery Validation With Data Annotations In MVC2?

Apr 8, 2010

I am trying to make some sense of this validation stuff in MVC2. I followed various walkthroughs, all them for betas/rcs... and I cant' get anythign to happen. Note: THIS JQUERY - NOT THE MS AJAX STUFF!I have referenced MicrosoftMvcJQueryValidation.js which i got got the mvc2 futures lib.

My model is:

[Code]....

The form bit of my ViewPage<User>:

[Code]....

As far as I can see the only additional thing that is being rendered is this:

[Code]....

Which is interesting/annoying for a few reasons. Firstly all of my annotations appear to have been ignored.Secondly FormId isn't even marked as required, and as this rendered text was taken from a page loaded with a null Model (add mode) the FormId field isn't in the form. Finally, this doesn't even result in any actual validation occuring (on the client side). All the server side validation is working fine.See I am using PasswordFor instead of EditorFor. Because someone at MS testing dropped the ball there. Yes EditorFor renders a password field, but it behaves differently to PasswordFor.. the value of the Password field is sent to the client (set in the value
attribute of the field). Fail.

View 8 Replies

MVC :: Data Annotations Or Service Layer Validation?

Feb 10, 2010

I'm creating a Asp.Net MVC application and I need help on whether I should chose Data Annotations or Service Layer Validation (e.g. if(Model.Name.Trim().Length == 0)?

View 5 Replies

How To Use DisplayName Data Annotations For Column Headers In WebGrid

Mar 9, 2011

I have a Car class that I'm trying to display in an MVC 3 view using the WebGrid helper. Below are the Car and it's metadata class.

Car class:

[MetadataType(typeof(CarMetadata))]
public partial class Car
{
// car implementation
}
Car metadata class:
public class CarMetadata
{
[DisplayName("Car Name")]
[StringLength(100, ErrorMessageResourceType = typeof(ValidationText), ErrorMessageResourceName="CarNameDescriptionLength")]
[Required]
public string CarName { get; set; }
}

View contents:

@model List<Car>
...
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 10);
grid.Pager(WebGridPagerModes.NextPrevious);
@grid.GetHtml(
htmlAttributes: new { id = "grid" },
columns: grid.Columns(
grid.Column("CarName", ?????)
));

GOAL: I'd like to figure out how to use the DisplayName data annotation as the column header text in the WebGrid (?????). Does anyone know how this is accomplished?

View 1 Replies

MVC :: Data Annotations, View Models & Multiple Controller Actions?

Feb 17, 2010

quick question: I have a view on my HomeController which is used to create a new 'model'. This view posts to a different controller to keep things tidy. The problem I am having is when I enter invalid details into the form, the rules I specified never seem to make it back to the original view and thus my validation messages or summary never get populated. Is there a way around this because I am using a view model with two IEnumerable lists in it.

View 5 Replies

MVC :: Does Client-side Validation Using Data Annotations Work With Lists

Jan 27, 2010

In my view data class I have a List.

[Code]....

I have all the properties of the class Person as required using Data Annotations.

[Code]....

In the View I loop the List like this:

[Code]....

Generated HTML:

[Code]....

Result:

Does not work at all.

Other things I've tried:

Tried using these HTML Helper methods instead:

[Code]....

Generated output:

[Code]....

Result:

Interestingly, when I trigger a validation on the first textbox, it fires simultaneously for all of the textboxes. The rest of the textboxes do not trigger validation at all.

Looking at the generated id and names for the textboxes and their corresponding error text span element, they areall identical.

Anyone figure out how to use Client Validation with Data Annotations with a List in the view data,
supporting Model Binding?

View 4 Replies

Possible To Use Data Annotations For LabelFor,ValidationMessageFor, EditorFor With Strongly Typed Resources?

Feb 26, 2010

I would like to use DataAnnotations in my ASP.NET MVC application. I have strongly typed resources class and would like to define in my view models:

[DisplayName(CTRes.UserName)]
string Username;

CTRes is my resource, automatically generated class. Above definition is not allowed. Are there any other solutions?

View 3 Replies

C# - Data Annotations Silverlight / Bind The Publisher To A Dataform And Have The Dataform Handle To Validation?

Aug 20, 2010

I have a webservice that supplies data (Publisher Object) to a silverlight project.

I want to bind the Publisher to a dataform and have the dataform handle to validation.

I would like to achive this by using DataAnnotations.

My question is..
Can I or how do you amend the Publisher object (Generated by the webservice) to add the DataAnnotations

View 1 Replies

Mvc2 Data Annotations Validation (Client Side Works, Server Side Doesnt?

Aug 12, 2010

I'm using an entity model with metadata annotations. My controller method looks like this...

if (!ModelState.IsValid)
{
return View(model);
}
else
{
UpdateModel(model);
repo.Save();
return RedirectToAction("Index");
}

If I enable client side validation in the view I'll get the error per the Attributes from the metadata class. If I take clientside validation out, error gets thrown from saving to the DB rather than return the view with an Error Summary.

This is the top portion of my view....

<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>

I've tried running without debugging (ctrl + f5) in debug and release mode as well as setting breakpoints and Debugging (f5) but it just seems weird to get Client side validation without server side validation. What am I missing here?

View 1 Replies

Should Data Annotations Be On The Model Or The View Model

Dec 15, 2010

I've been used to decorating data model classes with data annotation attributes, but the purist in me baulks slightly at including purely presentational attributes such as display format here. I am, however, quite happy to keep validation centric attributes here. One good reason I have to continue keeping all annotations etc. in the data model is that my view model aggregates data model classes, e.g.

my ViewModelBase.DetailItem<TEntity> property in the view model is just a reference to an entity class in my data model. If I wanted to move presentational annotations to the view model, I would have to quite radically revise my design to one where I duplicate data model properties in my view model and use an object mapping tool to populate view model objects based on data model objects.

[code]....

View 2 Replies

Forms Data Controls :: Validating TextBox Data Against Multiple Types Of Data

Dec 22, 2010

I m Using a GridView: Columns: "Ser_type" tells what type of data is it i.e. VC for Varchar, NU for Numeric, DT for DateTime etc, for the time being i m using datavalidation controlls at design time. this is not a good approach. I just wan to do is that, DataValidationControlls should be created at RunTime and TextBox should validate data at runtime only. i.e. if Data required in the TextBox is of Type VC then it should validate only at runtime, if DT then validate DateTime only at Runtime similarly for all dataType:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" >
</asp:ScriptManager>
<div>
<div>
<asp:Panel ID="Panel1" runat="server" Height="150px" Style="left: 0px; position: relative;
top: 0px" Width="970px">
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/Home.jpg" Style="position: relative" /></asp:Panel>
</div>
<div>
<asp:Panel ID="Panel2" runat="server" BackColor="PaleTurquoise" Height="350px" Style="left: 0px;
position: relative; top: 0px" Width="970px">
<asp:Label ID="lbl_Home" runat="server" Font-Bold="True" Font-Size="XX-Large" ForeColor="#404040"
Style="position: relative" Text="Welcome to AutoSoft Dynamics" Width="700px"></asp:Label> <br />
<table style="left: 0px; position: relative; top: 0px">
<tr>
<td colspan="2" style="height: 21px">
<asp:Label ID="lbl_messege" runat="server" Style="position: relative" Font-Bold="True" Font-Size="16pt" ForeColor="#0000C0" Width="100%"></asp:Label></td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblExpMessage" runat="server" Style="position: relative" Width="100%" Font-Bold="False" Font-Size="12pt" ForeColor="Red"></asp:Label></td>
</tr>
<tr>
<td style="width: 464px">
<asp:Button ID="Button1" runat="server" Style="position: relative" Text="Button" />
<asp:Button ID="Button2" runat="server" PostBackUrl="~/EmpDetails.aspx" Style="position: relative"
Text="Go to Details Page" /></td>
<td style="width: 162px">
</td>
</tr>
</table>
<br />
</asp:Panel>
<asp:Panel ID="Panel3" runat="server" BackImageUrl="~/Images/Footer.bmp" Height="50px"
Style="left: 0px; position: relative; top: 0px" Width="970px">
</asp:Panel>
<br />
<cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
BackgroundCssClass="modalBackground"
PopupControlID="Panel_Popup"
CancelControlID="btnRemindLater"
TargetControlID="Button1" >
</cc1:ModalPopupExtender>
<asp:Panel ID="Panel_Popup" runat="server" Width="540px" HorizontalAlign="Center" >
<br />
<table width="100%" style="left: 0px; position: relative; top: 0px; background-color: inactivecaptiontext">
<tr>
<td colspan="4">
<asp:Label ID="lbl_Title" runat="server" BackColor="Desktop" Font-Bold="True" ForeColor="White"
Height="28px" Style="font-weight: bold; font-size: 15pt; vertical-align: middle;
position: relative; text-align: center" Width="100%"></asp:Label></td>
</tr>
<tr>
<td style="width: 11px">
</td>
<td style="width: 583px">
<asp:GridView ID="GridView_Popup" runat="Server" AutoGenerateColumns="False" BorderColor="Navy"
BorderStyle="Solid" BorderWidth="2px" CellPadding="3" DataKeyNames="ser_no" EmptyDataText="No recored found"
Font-Bold="False" ForeColor="Black" GridLines="Horizontal" HorizontalAlign="Left"
OnRowDataBound="GridView_Popup_RowDataBound" Style="position: relative">
<EmptyDataRowStyle BorderColor="Navy" BorderWidth="2px" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl_ser_no" runat="server" Font-Size="1pt"
Text='<%# Bind("ser_no") %>' ForeColor="ActiveCaptionText" >
</asp:Label>
</ItemTemplate>
<HeaderStyle BackColor="GradientInactiveCaption" />
<ItemStyle HorizontalAlign="Left" Width="5px" ForeColor="ActiveCaptionText" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lbl_description" runat="server" Font-Size="Small" Text='<%# Bind("description") %>'
Width="110px">
</asp:Label>
</ItemTemplate>
<HeaderStyle BackColor="GradientInactiveCaption" Font-Bold="True" Font-Size="Small"
ForeColor="White" HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" Width="110px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Declared Value">
<ItemTemplate>
<asp:TextBox ID="txt_DeclaredValue" runat="server" CausesValidation="True" Font-Size="Small"
Text='<%# Eval("declared_value") %>' ToolTip='<%# Eval("ser_help") %>' Width="205px" MaxLength="50"></asp:TextBox>
</ItemTemplate>
<HeaderStyle BackColor="GradientInactiveCaption" Font-Bold="True" Font-Size="Small"
ForeColor="White" HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" Width="205px" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl_Mandatory" runat="server" Font-Size=".5pt" ForeColor="inactivecaptiontext"
Text='<%# Bind("mandatory") %>' Width="15px"></asp:Label>
</ItemTemplate>
<HeaderStyle BackColor="GradientInactiveCaption" Font-Size="Small" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" Width="15px" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl_ser_type" runat="server" Font-Size=".5pt" ForeColor="inactivecaptiontext"
Text='<%# Bind("ser_type") %>' Width="15px"></asp:Label>
</ItemTemplate>
<HeaderStyle BackColor="GradientInactiveCaption" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" Width="15px" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:RequiredFieldValidator ID="rfv_declaredVal" runat="server" ControlToValidate="txt_DeclaredValue"
ErrorMessage="*" >
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rfv_num" runat="server"
ControlToValidate="txt_DeclaredValue" Display="Dynamic" Enabled="false" ErrorMessage="Only (0-9)"
ValidationExpression="^[0-9]*$" Font-Size="10pt" >
</asp:RegularExpressionValidator>
<asp:RegularExpressionValidator ID="rfv_NonNumeric" runat="server" ControlToValidate="txt_DeclaredValue"
Enabled="false" ErrorMessage="Only (a-z/A-Z)" ValidationExpression="^[a-zA-Z'.s]{1,40}$" Font-Size="10pt" >
</asp:RegularExpressionValidator >
<asp:CompareValidator ID="cv_txtDate" runat="server"
ControlToValidate="txt_DeclaredValue" ErrorMessage="dd/MM/yyyy only"
Operator="DataTypeCheck" Type="Date" Font-Size="10pt" >
</asp:CompareValidator>
<asp:RegularExpressionValidator ID="rev_Decimal" runat="server" ErrorMessage="Only Decimal"
ControlToValidate="txt_DeclaredValue" Style="position: relative" Font-Size="10pt"
ValidationExpression="(?!^0*$)(?!^0*.0*$)^d{1,18}(.d{1,2})?$" />
</ItemTemplate>
<HeaderStyle BackColor="GradientInactiveCaption" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
</asp:TemplateField>
</Columns>
<HeaderStyle BorderColor="Navy" BorderStyle="Solid" BorderWidth="1px" ForeColor="#0000C0"
Height="25px" HorizontalAlign="Left" VerticalAlign="Middle" />
</asp:GridView>
</td>
<td style="width: 10px">
</td>
</tr>
<tr>
<td style="width: 11px; height: 26px">
</td>
<td style="width: 583px; height: 26px">
<table style="left: 0px; width: 100%; position: relative; top: 0px">
<tr>
<td style="width: 63px; height: 26px">
<asp:Button ID="btnSubmit" runat="server" Style="left: 0px;
position: relative; top: 0px" Text="Submit" OnClick="btnSubmit_Click1" />
</td>
<td style="width: 100px; height: 26px">
<asp:Button ID="btnRemindLater" runat="server" OnClientClick="winclose()"
Style="left: 0px; position: relative" Text="Remind Me Later" UseSubmitBehavior="False"
Width="120px" />
</td>
<td style="vertical-align: middle; width: 304px; height: 26px; text-align: right">
<asp:Label ID="lbl_LastDatePopup" runat="server" Font-Bold="False" Font-Size="Small"
ForeColor="Red" Style="position: relative" Width="100%"></asp:Label></td>
</tr>
</table>
<asp:Label ID="Label1" runat="server" BackColor="InactiveCaptionText" Style="position: relative">
</asp:Label><asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Please correct the mandatory fields labeled with * "
Height="1px" ShowMessageBox="True" ShowSummary="False" Style="position: relative" />
</td>
<td style="width: 10px; height: 26px">
</td>
</tr>
</table>
<br />
</asp:Panel>
</div>
</div>
</form>

View 4 Replies

Image Annotations Using Silverlight In .net 3.0?

Nov 26, 2010

I been working in a web applciation and want to annotate the image downloaded from the server at client side and once the user have added some text into the image that specified images must be saved on the server so that while rereving those images user should be able to view the annotated imags.How to achieve the above target.?I have tried following link which is in Jquery and add the annotations in the images...but it last until user close the browser.

http://code.google.com/p/jquery-image-annotate/

Besides this,they also given a solution to implement it the server side in the below link;

http://blog.flipbit.co.uk/2009/04/server-side-ajax-handler-for-image.html

But, the code written is using c# in MONORAIL..infact i could not understand the save,delete operations of the annotations. i been searching for the solution for more than a weak but could nt get it yet.. it using silverlight but as I am quite new to silverlight so send me some useful links for the same.

View 2 Replies

Validating Data Sent To A Web Method From JQuery

Nov 30, 2010

I have been thinking what is the right way to validate the data I am sending to a web method from jQuery ajax call. I have formerly used updatepanels to do my ajax, but am trying to shift to jQuery now and validation seems to get more complicated.

So obviously there are both client- and server-side validation options. At first I tried implementing jQuery validation plugin and got it working. But surely client-side validation is not good enough alone. Then I considered implementing regular asp.net validation to validate on the server. But what if a user tampers the input parameters after the validation happened. He could break the execution of the script in Firebug and change the input to whatever he wanted. So how can I either prevent that or implement validation in the web method?Here is my ajax call which sends a message to the server. [Code]....

You see I am sending three parameters (id of the person who this message is ment for, message type and message text). Even if I implement asp.net validation against input controls, a user might change those input values in Firebug, right? So I need to validate the input again in the web method? Or what would be the best way from the beginning?

View 6 Replies

Forms Data Controls :: Validating An Entire Column In Gridview Before Data Is Saved In Database?

Mar 24, 2010

I am using a bound gridview in ASP.NET 2.0. The gridview has the ability to edit/update and insert rows. One of the columns holds a number which represents a percentage. What I cannot figure out is how to ensure that all the rows in the gridview total 100% before being able to send the updates or newly inserted data to the database.

For example say there are 5 rows in the gridview, each row has 20% stored in the column so it adds up to 100% which is fine, the data is updated/inserted in the database. But say each row only had 15% totalling 75%, the user should not be able to send the updated/inserted data to the database until either they add a new row with a percentage of 25 or they edit the other rows for a cumulative total of 100%

I am not familiar with javascript or AJAX

View 6 Replies

ADO.NET :: Validating DropDownList Populated With Data From SQL DataTable

Dec 30, 2010

i have one simple question; do I have to... or is there any need to validate value from DropDownLists that are populated from SQL Datatables. I know how to validate them, but I am just concerned about potential SQL Injection, because those DropDownLists are going to be "Input fields" for a new Datatable, and insted of using TextBoxes, user will choose values from those DDL's and Submit them (INSERT INTO) to SQL Datatable. Is there a way for a "hacker" to insert his item value into DropDownList. I hop You understand what I mean!?

View 6 Replies

JQuery :: Retrieving Annotations Stored Into The Database?

Nov 30, 2010

Get function as on call of save function and delete function the annotation's entry would be updated in the database.But, The Get function is not drawing the marked annotations on the image.How it would work.?

View 6 Replies







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