How do I specify a strongly-typed html helper that uses a nested class of the model instead of the model itself? - asp.net-mvc-2

I am creating a strongly-typed search form in ASP.NET MVC 2 that posts to a results page via FormMethod.Get (i.e. the form inputs and their values are posted to the search results query string). How do I specify strongly-typed html helpers that use a nested class of the model instead of the model itself so that I don't get the dot notation for the input names in the query string?
My strongly-typed view model class looks like:
public class SearchViewModel
{
public SearchQuery SearchQuery { get; set; }
public IEnumerable<SelectListItem> StateOptions { get; set; }
...
}
The SearchQuery class looks like:
public class SearchQuery
{
public string Name { get; set; }
public string State { get; set; }
...
}
Doing this:
<%= Html.TextBoxFor(m => m.SearchQuery.Name)%>
will generated an input with name SearchQuery.Name, which will place &SearchQuery.Name=blah in the query string when the form is posted. Instead, I would prefer just &Name=blah, as only SearchQuery properties will have associated form elements.
I'm assuming I have to do something with the Html.TextBoxFor Linq expression, but I can't seem to get the syntax right..
Thanks for your help!!

One way around this is to make Name a propery of the ViewModel ie:
public string Name{
get{
return this.SearchQuery.Name;
}
}
And in the view:
<%= Html.TextBoxFor(m => m.Name)%>
Whether or not this is a good idea is another question.

Related

Automapper and lazy loading with EF and performance

I have a model like this
public class Exam
{
public int NewsId { get; set; }
public string Title { get; set; }
public string Description{ get; set; }
public string Program{ get; set; }
}
and a view model like this
public class ExamViewModel
{
public int NewsId { get; set; }
public string Title { get; set; }
}
and I do config Automapper like this
AutoMapper.Mapper.CreateMap<Exam, ExamViewModel>();
and in an ActionResult I used Automapper like this:
public ActionResult Exam()
{
var examsDb = db.Exams;
IEnumerable<ExamViewModel> examViewModel = AutoMapper.Mapper.Map<IEnumerable<Exam>, IEnumerable<ExamViewModel>>(examsDb);
return View(examViewModel);
}
and in view I loop through it
#model IEnumerable<AraParsESOL.ViewModels.ExamViewModel>
<ul>
#foreach (var e in Model)
{
<li>
#Html.ActionLink(e.Title, "Type", "Exam")
</li>
}
</ul>
My problem is that:
As you can see in the Model There are 4 properties but in viewModel there are only 2 properties.
How can i get only those 2 properties in viewModel and not the entire Model?
What happens here is that in view after each loop it goes and get the required column from the database but i want only those 2 properties and not going back to database.
i can get the database like this
db.Exam.ToList();
but it will cause the entire database gets back.
i want to use best practices here?
i know i can get the data from database by anonymouse type and select command but then what is the use of automapper?
what is the best solution here?
Don't use AutoMapper. It's not appropriate for IQueryable<T>. Instead, use LINQ projections:
public ActionResult Exam()
{
var examsDb = db.Exams;
IEnumerable<ExamViewModel> examViewModel =
from e in db.Exams
select new ExamViewModel
{
NewsId = e.NewsId,
Title = e.Title
};
return View(examViewModel);
}
If you look at the generated SQL, you will see that only the NewsId and Title columns are retured. It looks like the AutoMapper folks were interested in addressing this shortcoming, but I haven't heard anything about it since this.

Including Hierarchy in Entity Framework Query

I have an object hierarchy that looks something like this:
public class Book
{
public virtual List<Page> Pages { get; set; }
public virtual List<Paragraph> Paragraphs { get; set; }
}
public class Page
{
public virtual List<Paragraph> Paragraphs { get; set; }
}
I want to load the complete object hierarchy and am going about that like this:
Book book = (from b in context.Books.Include("Pages").Include("Paragraphs")
.Include("Pages.Paragraphs") where CONDITION).SingleOrDefault();
I find that book.Pages and book.Paragraphs are loaded, but book.Pages[i].Paragraphs is null.
Examining the database, the data looks correct (association columns are all correctly populated).
I also tried the lamda syntax, but do not see how that could work when the parameter is a collection rather than an entity, e.g. one can do something like this:
.Include(s => s.Paragraphs.Select(p => p.Id == 1)
but I do not see how one could use the lamda syntax to specify that the Paragraphs collection for each Page in book.Pages should be loaded.
Am I missing something, or is this a limitation of Entity Framework? If it's a limitation, how can I work around it?
In the actual code (not the code boiled down for the purpose of asking a targeted question, I was missing a virtual keyword. EF didn't complain about an inability to load the additional data requested through .Include("Pages.Paragraphs"), it just silently ignored that request.
public class Page
{
public /* was missing: virtual*/ List<Paragraph> Paragraphs { get; set; }
}

Understanding Forms in MVC: How can I populate the model from a List<>

Conclusion in Images, can be found in the bottom
I'm having some trouble to get how Forms work in MVC (as I'm a WebForms Developer and really wanna start using MVC in one big project)
I took the MVC2 Web Project and add a simple ViewModel to it
namespace TestForms.Models
{
public class myFormViewModel
{
public myFormViewModel() { this.Options = new List<myList>(); }
public string Name { get; set; }
public string Email { get; set; }
public List<myList> Options { get; set; }
}
public class myList
{
public myList() { this.Value = this.Name = ""; this.Required = false; }
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
public bool Required { get; set; }
}
}
Created a Strongly Typed View, passed a new object to the view and run it.
When I press submit, it does not return what's in the Options part... how can I bind that as well?
my view
alt text http://www.balexandre.com/temp/2010-10-11_1357.png
filling up the generated form
alt text http://www.balexandre.com/temp/2010-10-11_1353.png
when I press Submit the Options part is not passed to the Model! What am I forgetting?
alt text http://www.balexandre.com/temp/2010-10-11_1352.png
Conclusion
Changing the View loop to allocate the sequential number, we now have
<%= Html.TextBox("model.Options[" + i + "].Value", option.Value)%>
model is the name of our Model variable that we pass to the View
Options is the property name that is of type List
and then we use the property name
Looking at your UI it seems that you did not put the data from the Options member on it.
<% foreach (myList obj in Model.Options) { %>
// Add the object to your UI. they will be serialized when the form is submitted
<% } %>
Also check that you enclose the data in a form element
EDIT:
Sorry! I did'nt realized that you was filling the object inside the controller. Can you please show the code you have in the view?

Using "custom data types" with entity framework

I'd like to know if it is possible to map some database columns to a custom data type (a custom class) instead of the basic data types like string, int, and so on. I'll try to explain it better with a concrete example:
Lets say I have a table where one column contains (text) data in a special format (e.g a number followed by a separator character and then some arbitrary string). E.g. the table looks like this:
Table "MyData":
ID |Title(NVARCHAR) |CustomData (NVARCHAR)
---+----------------+-----------------------
1 |Item1 |1:some text
2 |Item2 |333:another text
(Assume I am not allowed to change the database) In my domain model I'd like to have this table represented by two classes, e.g. something like this:
public class MyData
{
public int ID { get; set; }
public string Title { get; set; }
public CustomData { get; set; }
}
public class CustomData
{
public int ID { get; set; }
public string Text { get; set; }
public string SerializeToString()
{
// returns the string as it is stored in the DB
return string.Format("{0}:{1}", ID, Title);
}
public string DeserializeFromString(string value)
{
// sets properties from the string, e.g. "1:some text"
// ...
}
}
Does entity framework (V4) provide a way to create and use such "custom data types"?
No. Not like that, anyway.
However, you could work around this by:
Write a DB function to do the mapping and then use a defining query in SSDL.
Using one type for EF mapping and another type like you show above, and then projecting.
Add extension properties to your EF type to do this translation. You can't use these in L2E, but it may be convenient in other code.

MVC 2 Validation and Entity framework

I have searched like a fool but does not get much smarter for it..
In my project I use Entity Framework 4 and own PoCo classes and I want to use DataAnnotations for validation. No problem there, is how much any time on the Internet about how I do it. However, I feel that it´s best to have my validation in ViewModels instead and not let my views use my POCO classes to display data.
How should I do this smoothly? Since my repositories returns obejekt from my POCO classes I tried to use AutoMapper to get everything to work but when I try to update or change anything in the ModelState.IsValid is false all the time..
My English is really bad, try to show how I am doing today instead:
My POCO
public partial User {
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
And my ViewModel
public class UserViewModel {
public int Id { get; set; }
[Required(ErrorMessage = "Required")]
public string UserName { get; set; }
[Required(ErrorMessage = "Required")]
public string Password { get; set; }
}
Controller:
public ActionResult Edit(int id) {
User user = _userRepository.GetUser(id);
UserViewModel mappedUser = Mapper.Map<User, UserViewModel>(user);
AstronomiGuidenModelItem<UserViewModel> result = new AstronomiGuidenModelItem<UserViewModel> {
Item = mappedUser
};
return View(result);
}
[HttpPost]
public ActionResult Edit(UserViewModel viewModel) {
User user = _userRepository.GetUser(viewModel.Id);
Mapper.Map<UserViewModel, User>(viewModel, user);
if (ModelState.IsValid) {
_userRepository.EditUser(user);
return Redirect("/");
}
AstronomiGuidenModelItem<UserViewModel> result = new AstronomiGuidenModelItem<UserViewModel> {
Item = viewModel
};
return View(result);
}
I've noticed now that my validation is working fine but my values are null when I try send and update the database. I have one main ViewModel that looks like this:
public class AstronomiGuidenModelItem<T> : AstronomiGuidenModel {
public T Item { get; set; }
}
Why r my "UserViewModel viewModel" null then i try to edit?
If the validation is working, then UserViewModel viewModel shouldn't be null... or is it that the client side validation is working but server side isn't?
If that's the case it could be because of the HTML generated.
For instance, if in your view you have:
<%: Html.TextBoxFor(x => x.Item.UserName) %>
The html that gets rendered could possibly be:
<input name="Item.UserName" id="Item_UserName" />
When this gets to binding on the server, it'll need your action parameter to be named the same as the input's prefix (Item). E.g.
public ActionResult Edit(UserViewModel item) {
To get around this, do as above and change your action parameter to item OR you could encapsulate the form into a separate PartialView which takes the UserViewModel as it's model - that way the Html.TextBoxFor won't be rendered with a prefix.
HTHs,
Charles
Ps. If I'm totally off track, could you please post some code for the view.