Linq To Sql - MVC2 - Set ViewModel Values With Retrieved From Db Object's Values With DataAnnotations

Jan 8, 2011

Prior to using a ViewModel, I could easily pass the "soon to be edited" object directly to the view without needing to fuss over setting individual properties etc as the View conveniently accepted the Employee type directly..

[HttpGet]
public ActionResult EditEmployee(int? id)
{
EmployeeRepository ER = new EmployeeRepository();
Employee SomeEmployee = ER.GetEmployee(id.Value);
if(SomeEmployee!=null)
return View(SomeEmployee);

But now I'm using a ViewModel with DataAnnotations attributes applied over the top of various properties for validation purposes. Which creates a problem.. After fetching the "soon to be edited" object from the db, setting the ViewModel's values is suddenly a whole lot more complicated. I can't simply pass the retrieved object straight to the view, as the View now expects the VMEmployee type instead. I would like to be able to do something like:

[HttpGet]
public ActionResult EditEmployee(int? id)
{
EmployeeRepository ER = new EmployeeRepository();
Employee SomeEmployee = ER.GetEmployee(id.Value);
if(SomeEmployee!=null)
return View(new VMEmployee(SomeEmployee));

All paths seem to lead to a huge constructor which manually sets the values of each individual property. But I never had to do that before when I wasn't using a ViewModel. Model binding was a blessing! My objects also have complex child objects, which my form is also collecting values for, so this would be a huge/verbose task against DRY principals. I don't even really want to use a ViewModel, but am forced to because I need two different DataAnnotations rule sets for different validation scenarios applied to the same object.

All I want to do is be able to have two different DataAnnotations rule sets for different scenarios. I.e. public-facing www site vs internal-facing admin site. DataAnnotations doesn't seem to be flexible enough to easily cater for this common need. I've tried AutoMapper, but it throws an error saying it can't map my object types, I suspect because Employee was auto-generated by LINQ to SQL. What is the most elegant way to achieve this while sticking to DRY principals?

View 1 Replies


Similar Messages:

Possible To Add Links To Retrieved Database Values?

Apr 27, 2010

I hope I can explain myself properly. What i'd like to do is be able to add a Search form where users can search various criteria based on my Orders table. I was hoping to add the capability to click on one of the OrderID's to display the fields from the Orders in the various text boxes on my form. This would allow the users to search, and update all in the same page. I have the data retrieval portion down pat, but am not really sure how to give them useful links. Is this possible? Or is there a better approach that I could take?

View 6 Replies

State Management :: How Session Values Are Remembered And Retrieved

Apr 22, 2010

when designing E-commerce website or shopping cart we call session value from login and we use it anywhere we need,but i want to know how session values are remembered and retrieved??i mean where they are stored and how it will be accessed

View 4 Replies

MVC :: Updating ViewModel Values On HttpPost?

Sep 3, 2010

I am just getting started with MVC after many years of WebForms development.

I have a very simple page with two textbox fields, one called Input where a user will enter something, and one called Output where I want to return some string after they post the form, much like a postback scenario in WebForms. I have the View connected to a ViewModel for strong typing.

The ViewModel:

[Code]....

The View:

[Code]....

The Controller:

[Code]....

The problem I have is that the output text "Here is some response" never gets displayed, even though I modify the value in the HttpPost method and return the viewmodel to the view. Unless (just tried it) I set the textarea to disabled with:

[Code]....

Can someone explain this behavior? It seems as some "magic" assumes that whatever was in the input fields before the HttpPost should also be there after the post, similar to what ViewState does in WebForms.

View 2 Replies

MVC :: Setting Default Values In A Viewmodel?

Jun 17, 2010

i am creating inintalizing a viewmodel with the following code in an create action;

[Code]....

the class applications is a LINQ to SQL Class and it has a property called VacancyID.

I want to default this VacancyID to '3'. From within this Action..

View 2 Replies

DataSource Controls :: Assign Dataset Values Retrieved From Database To Session Variables

Aug 16, 2010

I am looking to retrieve data from a database and assign those values to class objects which in turn will be turned into session variables. I am using an object datasource to retrieve the data from the database but I cannot find anywhere that shows how to assign these values to variables. The data is returned in a dataset. There is the added problem that there will be mulitple items returned which will have to be assigned to different arraylists of objects based on the a primary key in the database.

View 4 Replies

Maxlength Attribute Of A Text Box From The DataAnnotations StringLength In MVC2?

Mar 5, 2010

I am working on an MVC2 application and want to set the maxlength attributes of the text inputs.

I have already defined the stringlength attribute on the Model object using data annotations and it is validating the length of entered strings correctly.

I do not want to repeat the same setting in my views by setting the max length attribute manually when the model already has the information. Is there any way to do this?

Code snippets below:

From the Model:

[Required, StringLength(50)]
public string Address1 { get; set; }

From the View:

<%= Html.LabelFor(model => model.Address1) %>
<%= Html.TextBoxFor(model => model.Address1, new { @class = "text long" })%>
<%= Html.ValidationMessageFor(model => model.Address1) %>

What I want to avoid doing is:

<%= Html.TextBoxFor(model => model.Address1, new { @class = "text long", maxlength="50" })%>

Is there any way to do this?

View 3 Replies

Update A ViewModel In MVC2?

Mar 2, 2010

[HttpPost]
public ActionResult Edit(int id, FormCollection fc)
{
Movie movie =
(
from m in _ctx.Movie.Include("MovieActors")
where m.MovieID == id select m
).First();
MovieActorViewModel movieActor = new MovieActorViewModel(movie);
if (TryUpdateModel(movieActor))
{
_ctx.ApplyPropertyChanges(movieActor.Movie.EntityKey.EntitySetName,
movieActor.Movie);
_ctx.SaveChanges();
}
return View(movieActor);
}

However, I am not sure how to test this, and in general would much rather have the method take a typed model like:[HttpPost] public ActionResult Edit(MovieActorViewModel movieActor) Is this possible? What changes to my MovieActorViewModel class do I need to make in order to enable this? That class looks like this:

public class MovieActorViewModel
{
public Movie Movie { get; set; }
public Actor Actor { get; set; }
public PublisherDealViewModel(Movie movie)
{
this.Movie = movie;
this.Actor =
(
from a in this.Movie.Actors
where a.ActorID == 1 select a
).First();
}
}

The view is typed (inherits ViewPage) simple:

<% using (Html.BeginForm()) {%>
Movie Title: <%= Html.TextBoxFor(model=>model.Movie.Title) %><br/>
Actor Name: <%= Html.TextBoxFor(model=>model.Actor.Name) %>
<% } %>

View 3 Replies

C# - MVC2 - ViewModel For A Polymorphic Class

Jan 7, 2011

I'm making an MVC2 app to manage billing schemes. These billing schemes can be of various types, e.g. daily, weekly, monthly, etc. and all types have their specific properties. My class structure looks like this:

public abstract class BillingScheme { /* basic billing scheme properties */ }
public class BillingSchemeMonthly : BillingScheme
{
public string SpecificMonths;
}
//etc. for other scheme types

I retrieve a billing scheme through the base class using the billing scheme ID, and it gives me an object of the correct type. The property SpecificMonths maps to a database varchar field that contains a ;-separated string of month numbers. I want to split this to an array so I can create a list of checkboxes and I'd preferably do this with a facade property in a viewmodel. I could do it right inside the view but that seems to go against the MVC pattern.

The problem is I can only create this viewmodel specifically for a BillingSchemeMonthly, and I can't cast a BillingSchemeMonthly to a BillingSchemeMonthlyViewModel. I'd rather not implement a clone method in the viewmodel since the entire billing scheme is quite large and the number of properties may grow.

View 2 Replies

MVC2 Model Binding Does Not POST Back Hidden Values?

Jul 25, 2010

I have a /Register [GET] Action in the controller that pre-poluates a view-model with a string and an integer and returns: return View(myModel);I can see the string being populated in the textarea and the id being populated in a hidden input. Yet when the form gets POSTed, the string value is null and the int value is 0. I verified that both values are posted to the server but the model received in the POST action is missing those values.

View 1 Replies

C# - Int Values Get Automatically Converted Into Float Values On Binding The Text Values In Gridview?

Jun 29, 2010

I am getting int values from the stored procedure. But when i bind this datasource with the gridview i am seeing the values being converted into float. i am using Text='<% # Bind("Quantity") %' I wanna that to be displayed as int, with out zero'seg: let the value be 233, when i bind that its getting displayed as 233.00

View 1 Replies

C# - Best Way To Edit And Update Complex Viewmodel Objects Using Mvc2 And Entity Framework?

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

C# - Getting The Values From A Grouped Row Using LINQ?

Dec 17, 2010

I have the following class:

public class MySeat
{
public string Section { get; set; }
public string Row { get; set; }
public string Seat {get; set; }
}

I want to group a list of seats by the Section and Row so that I can make a comma seperated list of the seats.

var groupedSeats = seats.GroupBy(x => new { x.Section, x.Row });
foreach (var group in groupedSeats)
{
htmlWriter.Write(group.Key.Section);
List<string> seatNumbers = new List<string>();
foreach (var seat in group)
seatNumbers.Add(seat.Seat);
htmlWriter.Write(string.Join(@", ", seatNumbers.ToArray()));
}

Is there a better way to do this with LINQ? This is just a small portion of the code I'm trying to clean up, I'm curious if there is a better way to grab the seat numbers for display rather than creating a list, looping through the groups and then doing a string.Join on it.

View 2 Replies

ADO.NET :: Linq To Sql Using Distinct On Individual Values?

Jul 29, 2010

I have a database that is filled with documents. In the database there is the documents id, name and version. Two documents can have the same name and id but are seperated by different versions.For instance there can be two entries, id: A44, name: Dilbert was here. But they are version A and B.When retrieving these to a listview I wish to limit the documents shown to only one version. Doing so means that I am only to show one document with the same id. I only get the id and name to show in the listview so I thought that distinct might do the trick. But since the name can change throughout different versions this was no good.Basically I wish to retrieve all documents but with distinct id. How do I achieve this?

View 10 Replies

How To Store The Values In An Object

Mar 8, 2010

Except session and viewstate or a control with a value (including sqldatasource).Is there a way to store the value(s) in an object that will not loose the value if the page refresh?And also the best practice to hold sensitive value? I'm using viewstate with encryption for now but if p.e., have to hold a dataset then the page size will rise dramatically.

View 23 Replies

C# - How To Get Untyped Object's Values

Mar 29, 2011

I want to get an object typed properties values. Here is my code:

Type tip = Type.GetType(pair.Key.GetType().ToString());

object uretilenNesne = Activator.CreateInstance(tip);

uretilenNesne has correct type but I want to access uretilenNesne's properties values.

View 1 Replies

Get All Properties And Values Of An Object?

Feb 5, 2010

I am using logger to record all error information.

When log error informtion we need to

logger.error("User.UserID" & user.userID)

logger.error("User.pw" & user.pw)

And what I am trying to achieve is;

logger.error(myClass.getObjectInfo(user))

and I want myClass.getObjectInfo can list all of the object property along with values.

View 5 Replies

Linq To DataTable Not Producing Distinct Values?

Oct 19, 2010

I have a datatable which has been dynamically generated from FoxPro tables using a UNION Select statement. e.g.

SELECT * FROM x UNION SELECT * FROM y UNION SELECT * FROM Z ORDER By v_alue1

This produces a datatable with about 100 rows, each containing many fields, one of which is c_olor. From this datatable, I would like to select the distinct colors and then output in a dropdown.

I have a public class Color which just has one property which I can then use as the DataTextField and DataValueField for the dropdownlist

[code]...

However this never results in the distinct colors.

I have searched and searched for what I am looking for, and this seems to be one of the methods to produce a distinct set of results, but this and the others do not work.

My reasoning behind getting the colors this way, is that I need to get various other distinct values from the same UNION SELECT datasource, so would just do one DB call, cache the results, and then just used this cached datasource to retrieve all my distinct values.

View 2 Replies

Linq To DataSet - Handling Null Values?

Jan 30, 2010

I have a requirement to convert LINQ to DataTable.

I stole the following Extension Method from StackOverflow:

[code]....

View 2 Replies

ADO.NET :: Insert In ListView With LINQ - Generated Values?

Jan 21, 2011

I have a table in the database for users with the columns FirstName, LastName, DateUpdated, UserUpdated. Now, I display the fields FirstName and LastName but the last to fields are just for internal record keeping. I don't want the user to see or be able to edit them. However, I do want the DateUpdated and UserUpdated field to be populated upon every insert and update. The user id is in the session and I just take the current date for the DateUpdated field.

My question is: How can I write the UserUpdated and DateUpdated fields without the user providing any values?I had a couple of ideas:

- Modify the DataContext class to automatically compute the values. Don't know if that's a good idea. Also, my changes will be overwritten when I re-generate the DataContext class.

- Create hidden fields that hold these vlaues. For instance: <asp:HiddenField ID="user_createdHiddenField" Value='<%# Eval("UserUpdated") %>' runat="server" />. But how do I actually assign a value to the field?

View 2 Replies

MVC :: Extract Values From $.to JSON Object?

Mar 25, 2011

I have the following result in my controller from the $.toJSON method;

"[{"param":"Update Payment","value":"50.00"}]"

How do I extract the values from param: and value: ???

View 4 Replies

MVC :: Retrieve Values Of Each Object In The View?

Jan 12, 2011

I have created two objects and placed id ViewData , I dont Know how to retrieve values of each object in the view..

var t = new List<Table1>()
{
new Table1 {Id = 123400,Name="Kalees00"},
new Table1 {Id = 12340011,Name="Kalees0011"}
};
ViewData["ListValues"] = t;
return View(t);

View 6 Replies

ADO.NET :: How To Add Hard Coded Values To LINQ Query Result

Aug 31, 2010

I am running a LINQ query which populates a list used by a DropDownList, I need to insert an "Unassigned" value to the list. The function below queries the values correctly from the db but does not insert the "Unaasinged" value to the list.

[Code]....

View 2 Replies

C# - Bind The Values Without Duplicates From Database Into Dropdown Using LINQ?

Apr 2, 2011

I have a small issue binding the values into a dropdown using LINQ in ASP.NET code-behind.

var clientquer = from i in Entity.New_Bank select i;
//var q = (from s in names
// select s).Distinct();
// var getlendername = (from db in mortgageentity.New_Lender group db by db.Bank_Name into t select t.Key).ToList();
if (clientquer.Count() > 0)
{
ddlbankname.DataSource = clientquer.ToList();
ddlbankname.DataValueField = "Bank_ID2";
ddlbankname.DataTextField = "Bank_Name";
ddlbankname.DataBind();
}

It is binding with duplicate values, but I don't want bind duplicate values. I'm trying to solve this by using a group by clause, but it is not working.

View 2 Replies

How To Get The Values Of All Localizable Properties That Appear On A Page Object

Jan 28, 2011

I'm working on an application that uses an approach to localization where they just call a translate function for every piece of text on a page. It leads to a lot of redundant code that looks like this (psuedocode):

function page_load():

translateControlText(control1, language);
translateControlText(control2, language);
translateControlText(control3, language);
translateControlText(control4, language);
translateControlText(control5, language);
translateControlText(control6, language);
translateImageAlt(image1, language);
100 more lines of this on a single page

The application is massive, so I don't have the opportunity to rewrite the translation logic. However, I think I could just loop through all of the controls on a page, check their type, and translate the appropriate property. At least then I would just have to call 1 function per page, and then throw it in a base page or master. However, I probably wouldn't want to translate certain things, such as table cells. Regardless, there is an attribute called Localizable that is on many properties such as Control.Text and Image.Alt. I'd like to be able to get a list of every string on the Page that is stored in a Property marked Localizable. Is this possible? Is this possible without reflection?

View 2 Replies







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