MVC :: Binding Of Complex Entity Turns Into Validation Error?
Aug 28, 2010
consider classic example: Product and Category editing Product in dropdown Id of Category is selected - Category mapped as object with all fields empty except Id when submitting Product edit form - validation gives an error: "Category name is required" (I have Required attribute on Category Name property)
How deal with such errors if I want to use built-in validation (
[Code]....
Writing custom data binder which would fill all such id-only-objects with values from database comes to mind.
upd: I did small research of mvc code and found out that validation happens before binding - so this solution would't work.
View 13 Replies
Similar Messages:
Mar 15, 2010
In my past I had created the following web page in web forms and I'm learning asp.net mvc right now , I had given it a tought and I run into conclusion I really wont know how to do the same page with asp.net mvc
before explaining you the actuall problem I would explain you the Model The model is a pretty simple , it for few columns which are bool , and a lot of them which are varchar(MAX) The View is built the following way
the bool parts of curse got a check box but the varchar parts are the complicated ones In my web form page i got the following code for each varchar property in my database
[Code]....
my server script gets the following page apon submit and checks if radio button 1 or 2 is selected if 1. it inserts the link as it is into colmn property while if it is 2. it saves the file on the server and saves the file location into the colmn property.
View 3 Replies
Jan 26, 2010
I'm having trouble finding a good tutorial on binding complex lists to an object. Essentially we have currencies that are user defined, we need to generate a form for each currency to allow the user to input exchange rates. I think I'm doing my list properly according to this post, however I'm not getting any data bound. here is my ASPX snippit.
[Code]....
Here is my form data object and associated objects.
[Code]....
Here is the html that is rendered.[Code]....
I'm having trouble finding a good tutorial on binding complex lists to an object. Essentially we have currencies that are user defined, we need to generate a form for each currency to allow the user to input exchange rates. I think I'm doing my list properly according to this post, however I'm not getting any data bound. here is my ASPX snippit.
[Code]....
View 1 Replies
Jun 8, 2010
I am very new to entity, sql, c#, and asp.net so this might be something easily fixed. I am attempting to display all the inactive products stored in my table called products in a datagrid.
var productQuery = from b in solutionContext.Version
where b.Product.Name == search && b.Product.ActiveNumber > b.VersionNumber
select new Product
{
Name = b.Product.Name,
Description = b.Product.Description,
ID = b.ID,
LastNumber = b.Product.LastNumber,
MiddleNumber = b.Product.MiddleNumber,
RSTATE = b.RSTATE,
ActiveNumber = b.Product.ActiveNumber,
LastModified = b.Product.LastModified,
ParentID = b.Product.ParentID,
ProductType = b.Product.ProductType
};
ProductsGrid.DataSource = productQuery;
ProductsGrid.DataBind();
I am getting this error: $exception {"The entity or complex type 'SolutionsModel.Product' cannot be constructed in a LINQ to Entities query."} System.Exception {System.NotSupportedException}
View 1 Replies
Feb 18, 2011
If I have Database Stored Procedure retrun Complex type (Contain from Columns for 2 tables) ( Composite) and No Relation between them so i can't use Navigation Property ... so how can I use That in ADO.NET Framework specially when i try to use Add Function Import i didn't find any thing else None, Scalars, Entites.
View 1 Replies
Jun 11, 2010
I'm trying to use formview in order to do insert of a new entity object (called Customer) Customer has a reference to another entity called Address. How can I fill both of them in the same formview?
View 1 Replies
Feb 20, 2011
I want to be able to update a model and all its collections of child objects in the same view. I have been referred to these examples: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx and http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ .
For example, I have an object Consultant, that has a collection of "WorkExperiences". All this is in an Entity Framework model. In the view, the simple properties of the Consultant object is no problem, but the collection I cannot get a textbox to show up for. I tried following the examples in the links above, but it doesn't work. The problem is, in those examples the model is just a list (not an object with a child list property). And also, the model again is an EF model. And for some reason that doesn't seem to work as in those examples.
[Code]....
This stuff with the EditorTemplate works fine in Phil Haack's sample project, which I downloaded to try, but here, with the EF model or whatever the problem is, I don't get any textbox at all. The table in the view is just there as a test, because in the table I do get the rows for WorkExperiences, whether I add an empty WorkExperience object or fill out its properties doesn't matter, the rows show up for each object. But again, no textbox...
View 2 Replies
Apr 2, 2010
I have a table in my database with a one to many relationship to another table, which has a relationship to a third table:
[Code].....
This seems to work fine. My question to you good folks: Is there a correct way to do this? I tried following the making a custom model binder per the blog link I posted above but it didn't work (there was an issue with reflection, the code expected certain properties to exist) and I needed to get something going ASAP. PS - I tried to cleanup the code to hide specific information, so beware I may have hosed something up.
View 1 Replies
Apr 15, 2010
[Code]....
What I want to achieve is the ID of the property: item.Item.ID to be bound to the ID from the (route)URL. However I can't get it to work. I tried using [Bind()] attribute.
I fixed it now using a hidden field in the form like so:
<%= Html.HiddenFor(model => model.Item.ID)%>
However this feels a bit icky. I'd like to know if there is a better cleaner way of doing this?
View 1 Replies
Apr 21, 2010
I'm trying to implement a recipe search page that allows users to specify search criteria by selecting checkboxes that match desired recipe attributes. All the data is stored in a database uing tables with 1 - many relationships. Each recipe can have multiple attributes from any of 5 attribute tables. I want to find all the recipes that match the user-selected criteria and display them in a grid. For example, the user may want a breakfast (attribute 1) recipe that is made with fruit and milk (attributes 2 and 3), is low-fat and high fiber (attributes 4 and 5), and takes less than 15 minutes to prepare (attribute 6). The query for this example might look something like:
SELECT distinct recipes.name, recipes.difficulty, recipes.preptime, recipes.cooktime
FROM recipes, recipeMeals, recipeDishes, recipeFoodGrps, recipeNutrients, recipeFixTimes
WHERE recipes.id = recipeMeals.recipeId and recipes.id = recipeDishes.recipeId and recipes.id = recipeFoodGrps.recipeId and recipes.id = recipeNutrients.recipeId and recipes.id = recipeFixTimes.recipeId and recipeMeals.mealId in (1) and
recipeDishes.dishId in (5) and recipeFoodGrps.fdGrpId in (1, 6) and recipeNutrients.nutrAttsId in (2, 3) and recipeFixTimes.fixTimeId in (1)
I' can generate the SQL but can't figure out how to bind it to a grid control. No could I see how to get any of the data controls to build the query for me. Is there a way to say "execute this query and display the results in a GridView"?
View 4 Replies
Jan 6, 2011
I am using ASP.Net MVC2 and LINQ to SQL. I am using DataAnnotations and model binding in conjunction with a Form/View and its working beautifully well. Loving that.. My view is an "Add new Employee" form that's adding a new "Employee" complex object. Every Employee also has a child complex object called an "Address".
I am using the bound Html helpers in the view, such as Html.TextBoxFor(model => model.NewEmployee.FirstName) for example. Working beautifully well, validating beautifully well both client and server and coming into the controller fully populated and ready to be saved! Exciting.. ModelState.IsValid returns true and I go to save the new Employee.
The Employee is created fine but the system also creates a blank/new Address record in my Addresses table even when the Address fields are blank! How can I prevent any Address from being created, in situations where I ONLY want to create a new Employee with no Address. An example is when the user supplies an existing Address, then I wish to simply set the new Employee's AddressID to that of an existing physical address (I hope that makes sense). But it could apply to any situation where you need to create a new complex object, but you don't wish for LINQ to create any of its child complex objects. I have tried setting NewEmployee.Address = null after it is received in the controller, but even after that, a blank/new Address is still created. Even if I try NewEmployee.Address = SomeExistingAddress, it does correctly link the Employee to the existing Address, but it STILL goes off and creates another redundant new/blank address record! Which is really weird..
View 10 Replies
Jan 5, 2011
I have a "Create New Employee" ASP.Net MVC form. My complex object is an Employee and an Employee has an Address, which is another Complex object. On my View/Form I collect all required values for both the Employee and the Address. I'm using the bound HTML helpers such as: Html.TextBoxFor(model => model.EmployeeAddress.StreetName)
AND
Html.TextBoxFor(model => model.NewEmployee.FirstName)
This is all working beautifully well. Model binding is working like a dream, both server side and client side validation using DataAnnotations is working beautifully well and I am nicely receiving my populated complex objects as expected in the Controller.. Now I'm trying to save.. The Employee should always be newly created, because its an "Add New Employee" form. But sometimes the Address is an existing Address and I don't want to insert another one. Rather, I just want to link the Employee to the existing AddressID of the one that already exists in the database.
So I wrote a nifty GetExistingOrCreateNewAddress(Address PostedAddress) method which works great so I end up with the correct Address to use and link to the about to be saved Employee object. This is all happening in the same DataContext, so no problems there..
BUT even when I link the about to be saved Employee object to an existing Address, on save a new/empty Address row is created in my Addresses table. Even though the newly created Employee does link correctly to the existing Address I told it to! Why is it so??? And how can I save the new Employee without LINQ automatically creating a blank Address for me. Because I'm explicitly specifying an existing Address it should be linked to instead!
[HttpPost]
public ActionResult CreateEmployee(EmployeeDetailsViewModel NewEmployeeDetails)
{
if (ModelState.IsValid)
{
EmployeeRepository ER = new EmployeeeRepository();
// Fetch or Create the appropriate Address object for what has been entered
Address ActualAddress = ER.GetExistingOrCreateNewAddress(NewEmployeeDetails.EnteredAddress);
// Link this Address to the "about to be saved" Employee
NewEmployeeDetails.Employee.Address = ActualAddress;
// Lock it in..
ER.SaveNewEmployee(NewEmployeeDetails.Employee);
View 2 Replies
Oct 15, 2010
We know that using something like Bind("CustomerName") can be used in the Text property of a label control inside a gridview, where CustomerName is a property of the object whose collection is bound to the gridview. If that property is of a complex type (object of another class), how do we use a property of that inline object as a binding for the gridview column?
View 3 Replies
Jan 15, 2010
I'm been working on a GetRuleViolations() method for my User class, but I'm getting a little hung up on on something:
What happens when different actions require different business rules?
My User table has the following columns: Id, UserRoleId, Username, and Password. Several actions involving User are possible (create new user, edit user, set/reset password, and log in), and the business rules for each are not always the same.
For example, when users log in, they are required to enter a password, but when admins create a new user, entering a password is not even an option. And in the case of setting/resetting a password, the password needs to be entered twice, and the two values need to be an exact match. What is the best way to handle this complexity? Is there some kind of design pattern to allow the right GetRulesViolations() method to be selected for the right circumstance?
View 2 Replies
Feb 23, 2011
I want to display an editor for a type User. User contains a field Address of type Address. I made an editor template for the type Address so that it is reusable.
I don't want the field Address to be required for creating a user. But some fields are required for Address, for example country, state etc.
I want to validate Address if I receive any data for it, if I don't receive anything, then I don't want to return any validation error to the UI for Address. I would return only validation errors for User then.
View 1 Replies
Oct 18, 2010
I feel like I am fighting against the current when I develop ASP.NET Webform apps. I frequently run into the same problems, and while I eventually find some kind of workaround i'm never fully satisfied with the results.
Here is an example of a typical problem:
The design requires a grid or grid-like result set. This result set is pulled from a database, however, there are additional controls on each row that are not data bound, but their contents are used to insert data into other records.
A good example of this would be displaying a list of products, then adding selected products to a shopping cart based on values entered into quantity fields, and options selected per product. Throw into the mix that you have to allow multiple lines to be added to the cart at the same time, and it starts to get more complex.
Let's add to that mix that you can't select certain products together (mutually exclusive), that you can only select a certain number of one product, but not another, that prices may change while the user is selecting their items, that you you get an overall discount per item based on quantity purchased (both per item and overall order), that you are using a line of credit and cannot exceed the line of credit, nor can you buy more of a given item than an arbitrary amount set in your account or in the product by your account representitive (think certain over the counter medications that the government limits how many you can buy), etc.. etc.. etc..
What starts out as a simple grid with an add to cart becomes a hopeless mess of business logic, which then of course requires validation and notification to the user of various errors in their choices.
How does one deal with very complex data entry schemes in asp.net? How do you even begin to design a piece of software to do all this?
View 2 Replies
Feb 3, 2011
I have a question regarding validation of drop-down list values. I have a view that is bound to a view model type called ReservationData.
This object contains a property CustomerVehicles of type List<VehicleData>. VehicleDatahas two int properties VehicleMakeId and VehicleModelId.
On my view I am trying to loop over the number of items in the CustomerVehicles collection and displaying two dropdowns for each, a vehicle make dropdown and a vehicle model dropdown usingDropDownListFor.
When I try to submit and validate I do not see any validation errors displayed on the screen.
Just in case you are wondering I have added a ValidationMessageFor for each dropdown as well. I am not sure if this is an issue with the structure of my view model and its complexity and how the controls need to be named or how the ids need to be set.
Here is the code for the looping over the collection:
[Code]....
View 11 Replies
Oct 13, 2010
We have an ASP.NET MVC site that uses Entity Framework abstractions with Repository and UnitOfWork patterns. What I'm wondering is how others have implemented navigation of complex object graphs with these patterns. Let me give an example from one of our controllers:
[code]....
It's a registration process and pretty much everything hangs off the POCO class Person. In this case we're caching the person through the registration process. I've now started implementing the latter part of the registration process which requires access to data deeper in the object graph. Specifically DPA data which hangs off Legal inside Country.
The code above is just mapping out the model information into a simpler format for the ViewModel. My question is do you consider this fairly deep navigation of the graph good practice or would you abstract out the retrieval of the objects further down the graph into repositories?
View 2 Replies
May 18, 2010
I have a question about model binding. Imagine you have an existing database entity displayed in a form and you'd like to edit some details, some properties eg createddate etc are not bound to the form, during model binding, these properties are not assigned to the model as they are not on the http post data or querystrong etc, hence their properties are null. In my controller method for update , Id just like to do
public ActionResult Update( Entity ent)
{
//Save changes to db
}
but as some properties are null in ent, they override the existing database fields which are not part of the form post data, What is the correct way to handle this? Ive tried hidden fields to hold the data, but model binding does not seem to assign hidden fields to the model.
View 1 Replies
Feb 1, 2011
I am using the ADO.NET Entity Framework for loading data from the database. The classes are directly mapped to database tables in the database. The problem is that these classes are not optimal for binding to the UI elements. As a result of this I have some custom entities which are populated at the service layer and returned. It is these custom entities (classes) to which I bind the UI elements. My questions on this are1. Is populating these entities at the service layer the most appropriate way to do this. I personally do not think so because if we introduce some additional UI elements which need different entities then I have to modify the service layer again.2. What is the best approach/pattern to get this done.
View 2 Replies
Feb 19, 2010
got a question regarding form validation via entity partial class. I created my edmx-file with the Entity Data Model. Now I am trying to validate my form inputs via this partial class:
[Code]....
Edmx file and partial class are in the same namespace. But the partial class does not get fired. My controller file looks like that:
[Code]....
View 16 Replies
Nov 30, 2010
jQuery validation is working fine on my machine, when i pushed it to test server it won't it's throwing some errors which is kind of surprising.These are the errors I am getting: $.validator is null or not an object...I've never gotten this error before and it throwing an error when I declared a variable like var isValid.I don't know what to do. I am doing the custom validation methods not in the document.ready(). Does this cause this error? I wonder because all jquery validations are passing and hitting the server side validations.
View 1 Replies
Feb 17, 2010
I have an ObjectDataSource that is bound to a GridView. The object accepts a parameter from a TextBox. The problem I have is when I use a CustomerValidator with a ServerValidate event, the ObjectDataSource would still attempt to perform a DataBind despite the fact the the customer validator has returned false. The following is the code in the ASPX page.
<asp:TextBox ID="sittingDate" runat="server" />
<asp:CustomValidator ID="DateValidator" runat="server" ControlToValidate="sittingDate" OnServerValidate="DateValidator_ServerValidate" />
<asp:ObjectDataSource ID="BatchDataSource" runat="server" OldValuesParameterFormatString="original_{0}"
SelectMethod="GetOrCreateSittingBatch" TypeName="BatchBLL" OnSelected="BatchDataSource_Selected" OnSelecting="BatchDataSource_Selecting">
<SelectParameters>
<asp:ControlParameter ControlID="sittingDate" Name="batchDate" PropertyName="Text"
Type="DateTime" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:GridView ID="BatchGridView" runat="server" DataSourceID="BatchDataSource">
In the Custom Validator I have
protected void DateValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
/Ensure that the entered data is a date.
string input = args.Value;
DateTime result;
args.IsValid = DateTime.TryParse(input.TrimEnd(), out result);
}
How do I stop the ObjectDataSource from data binding when validation has failed?
View 2 Replies
Mar 3, 2010
why when i'm loging in the loginName turns in to the name of my server and not the name of the username ... ? give some tutorials or articles about loginview.
View 2 Replies
May 12, 2010
I have a label in ASP.NET 2.0(C#). The label should display a dutch language text that is "Sähköpostiosoite", I tried setting the Label.Text both from markup and code-behind but what I see in the browser response is "Sähköpostiosoite".
Originally assigned string "Sähköpostiosoite" get replaced with "Sähköpostiosoite".
View 3 Replies