subsonic, mvc and activerecord - asp.net-mvc

i am using subsonic 3.0 and active record with a mysql database
now everything is fine, but i cant seem to create views see example:
public ActionResult Index()
{
return View(contact.GetPaged(1,20));
}
now normally i would right click and choose Add View
i would then choose strongly typed and find the class for the repositary
however for some reason the only classes i get showing up are for subsonic only
but expect to see the new class from the new generated graniteMysqlDB
if anyone could please advice i would be most grateful as there doesent seem to be
any forum links or anything for subsonic.
thanks

okay i have solved the problem, but the answer is here should anyone need it or wants to know what happened.
i put my TT files into the models folder, my namesspace should have been test2.Models
however it was test2
also i needed the using directive of using test2.Models; at the top of my page.
still get an error where i have to correct the view on the inherites it puts
i have to change this to
very nice now is this subsonic very very fast loading compared to other stuff i have used.
ta

Related

Where should I place sub-structures within a MVC controller

I am trying to build a controller that will enable the user to add/remove subcontent to an item.
Think of it like a document where you can add different types of sections, like headlines, paragraphs, images etc. (they each have their own attributes so they are in seperate tables in the SQL)
My question is where should I put the code to handle the different types of subsections within this "document controller"?
They are all attached to this "document"/entity through database relations, but should I make a "crudl" controller for each type or should I do a base kinda crudl and then let them all inherit this?
I've looked into "Models" and "service layers" - is that the right way to do it?
I am still rather new with MVC, using C# and ASP.net I was hoping for someone to give me a hint in the right direction.
Nb. please let me know if I should rephrase the question. Didn't know what to ask to get the right answer here.
Specs: I use EF 4.x and MVC3 will upgrade to latest when available, if needed.
In hope of some clever answers or guidance. Thanks in advance people. And yes, I have tried to Google too. Don't know what to search for, so I come here.
where should I put the code to handle the different types of subsections within this "documentcontroller"?
The code for this would ultimately go into a controller action which you then handle and update the database accordingly. There are multiple ways of doing this, you could be generic e.g.
[HttpPost]
public ActionResult AddSection(string type)
{
switch (type)
{
case "HEADING":
// add new heading to database
case "PARAGRAPH":
// add new paragraph to database
}
return View(type);
}
Or you could be specific e.g.
[HttpPost]
public ActionResult AddHeadingSection()
{
// add to db
return View("Heading");
}
[HttpPost]
public ActionResult AddParagraphSection()
{
// add to db
return View("Parapgraph");
}
The above is just really pseudo code to give you a rough idea of how you could do it with minimal effort. IN a real life situation you will probably be posting extra information along with it e.g. AddHeadingSection(HeadingModel model). It's really up to you how you go about implementing this.
Also, you might want to consider using AJAX over full postbacks it would make your app a bit slicker.

How to update Model when binding to a ViewModel?

I have an [HttpPost] action method signature like this:
[HttpPost]
public ActionResult Edit(ExistingPostViewModel model)
{
// Save the edited Post.
}
Now, in the past (when i didn't use ViewModels, e.g R&D), i had an implementation of an Edit method like this:
[HttpPost]
public ActionResult Edit(Post model)
{
var existingPost = repo.Find(model.Id);
TryUpdateModel(existingPost);
repo.Save(existingPost);
return RedirectToAction("Success", existingPost.Id);
}
Which worked great.
But i'm confused how to adapt the above to the ViewModel approach.
If i do this:
TryUpdateModel(existingPost)
With my ViewModel approach, not much happens. No errors, but nothing is being updated because MVC won't know how to update a Post from a ExistingPostViewModel (before it was Post -> Post).
Now, i'm using AutoMapper. So i thought i could map from the ViewModel to the Post, then save the post.
But then im basically overriding everything. Which i don't want to do and defeats the point of the cut down ViewModel.
Can anyone un-confuse me?
This seems like a really common scenario, and i am totally stumped as to how people solve this. I can only see 3 possible solutions:
Don't use a ViewModel in the HTTP POST. As i said i did this in the past for R&D and it works, but now i see how my View's have evolved (validation, simplicity), and i can't compromise that just for the sake of this problem.
Don't use TryUpdateModel. Possibly, but then how would i merge in the changes?
Use left-to-right. Ugh. But at the moment this seems to be the way im leaning.
Someone please give me solution #4! :)
BTW, i'm using ASP.NET MVC 3, Razor and Entity Framework.
I actually ran into this exact same issue in a project I'm currently working on. As much as I wasn't a fan of it, I ended up doing the left to right approach and manually mapping my viewmodel data back to my entity.
The only nice thing about this approach is it does give you more control. Since I started using more compound viewmodels, where you actually have fields from more than one entity in your viewmodel, it started making more sense to do things this way.
I'm also using AutoMapper, and you're absolutely right, it does get awkward when you're trying to do a simple update operation. Wish I had some super clever workaround for you, but the "old fashioned way" seems to get the job done best for the work I've been doing.
Not sure if this will help, but it is working for me. I have my underlying domain table as a Visitor Object. My viewmodel contains the Visitor Object plus a couple of IEnumerables for dropdowns.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id)
{
Visitor Visitor = new Visitor();
Visitor = db.Visitors.FirstOrDefault(v => v.VisitorID == id);
UpdateModel(Visitor, "Visitor");
db.SaveChanges();
return RedirectToAction("Index");
}
The UpdateModel works off my viewmodel because of the "Visitor" string telling it what values to compare.
For simple things where you don't have to run any controls prior to implementing the update what you are doing is okay (db.get(), and then update).
When things get complicated, you have to load the entity, and then select and apply user's changes from the view model, property by property. In those cases, you end up writing Update methods, which gets the new data as input, and then you load the existing entity, then compare states, and take the required actions based on the view model data. Actually in this case, probably you wont have an Update method but will have behaviors, like CancelPost, AddComment, EditPost (which also logs the edit reason), AddTagsToPost etc.

Include in enity framework 4

I've been using enity framework that came with 3.5sp. And now I've redone things for enityframework 4 and asp.net mvc 2. I've come across something (which worked in my previous version and asp.net mvc 1.0).
I have this:
public IQueryable<Booking> GetBookings()
{
return from b in _entities.Bookings.Include("BookingObject")
select b;
}
And in my controller I have:
return View("Index", new BookingsViewModel
{
Bookings = _br.GetBookings().ByDay(DateTime.Today)
});
And it doesnt seem to include the "BookingObject"-entity, so I can type like <%= Model.Bookings.BookingObject.BookingObjectName %> in my view.
What might be missing here? Do I need to turn something on in the diagram for it to include entities or?
/M
No, it should work exactly as before. I'm assuming you have a navigation property BookingObject on your Booking item - but then the .Include() would error out if you didn't. I don't think there's anything else you need to set up, or at least not that isn't done by default. I'd verify the definition of the navigation property in the .edmx editor at least.
You're definitely using the final RTM EF4 code? We hit a bug in the final RC building incorrect SQL and returning no results for one specific include sequence, but it was a lot more complex than that.
Failing that I would use SQL Server Profiler to trace out the SQL it's using and try and debug that.

lessons learned or mistakes made when using asp.net mvc

what are your top lessons learned when starting asp.net mvc that you would highlight to someone starting out so they can avoid these mistakes?
Use Html.Encode() everywhere you print data, unless you have a very good reason to not do so, so you don't have to worry about XSS
Don't hardcode routes into your views or javascripts - they're going to change at some point, use Url.Action() instead
Don't be afraid of using partial views
MVC is no silver bullet, first evaluate if it's indeed the best tool of choice for solving your problem.
Don't forget the "Unit Tests" part of the pattern.
Try to always use a ViewModel to pass data between the Controller and the View.
You may think you don't need one, you can just pass your model around, but suddenly you need a list box with several options for editing a model, or displaying a message (not validation message) and you start adding items to the ViewData, with magic strings as keys, making the app harder to maintain.
There are also some security issues that you solve with a ViewModel.
For instance:
class user:
int id
string name
string email
string username
string password
Your view let's the user change his name and email and posts to the action
public ActionResult Edit(User user)
{
--persist data
}
Someone could tamper your form and post a new password and username and you will need to be very careful with the DefaultBinder behavior.
Now, if you use a ViewModel like:
class userEditViewModel:
int id
string name
string email
The problem is gone.
Whenever it is possible make your view typed
Avoid logic in your views
stay away from the HttpContext
Get Steve Sandersons Pro ASP.NET MVC Framework
Debug into the Sourcecode
If you make a Controller method with a different parameter name from id for a single parameter method, you have to make a new route. Just bite the bullet and use id (it doesn't care about the type) and explain it in the comments.
Makes sure you name your parameters with RedirectToAction :
return RedirectToAction("DonateToCharity", new { id = 1000 });
You lose your ViewData when you RedirectToAction.
Put javascript in seperate files, not into the view page
name of the controller :)
unit test Pattern
Don't use the Forms collection, use model binding.
Try not to use ViewData, create a ViewModel.
If you have a loop or an if in your View, write an HTML helper.
Kindness,
Dan
Don't let your controller become a fat one and do too much work. I've seen 1000+ line controllers in the past and it just becomes an absolute nightmare to understand what's going.
Utilise unit testing for your controllers to ensure that dependencies are kept under control and that your code is testable.
Don't get drawn into letting jQuery and fancy clientscript define the behaviour of your application, try and use it as sparingly as you can and let it enhance your application instead.
Use partial views and HTML helpers whenever possible to ensure that your Views do not become unwieldy and a maintenance nightmare.
Use a ViewModel whenever possible.
Use a dependency injection framework to handle your dependencies (MvcContrib has several controller factories, though it's simple enough to roll your own).
Use a different controller for every section of your site (e.g., Home, Account)
Learn how to use ViewData and TempData
Learn what's the use of RenderPartial

Problems with model using LINQ to SQL when adding a strongly typed view

I am trying to create a simple task manager solution based on the Nerd Dinner tutorial
weblogs.asp.net/scottgu/archive/2009/04/28/free-asp-net-mvc-nerddinner-tutorial-now-in-html.aspx.
EDIT: I have removed the http:// on these urls because I have not got enough rep to add links into a post.
I have built my model as shown here: nerddinnerbook.s3.amazonaws.com/Part3.htm
It is identical except that Dinner is a task and RSVP is a project.
Relationship task.projectId -> project.projectId
I have more fields in these tables but I have kept the public partial task class in the model simple so far to match the tutorial.
My question is that when I try to add a new view and in the dialog I select "strongly typed view" my model class for the task does not show up in the drop down, anyone know why??
Probably a bit vague, i am just trying to get some ideas on why this could be happening.
I thought maybe my namespace was incorrect somewhere or my class was not public but it is.
I have got a reference to my repository in my controller by doing
TaskRepository taskRepository = new TaskRepository();
and the controller has a using reference to TaskManager.Models;
All confusing me.
I don't know how the dialog picks classes (other than it requires a clean compile), but you can just choose any random class and then edit the first line of the resulting aspx to substitute the class you prefer.

Resources