MVC: How to work with entities with many child entities?

后端 未结 5 2154
温柔的废话
温柔的废话 2020-12-28 22:13

In the current examples on ASP.NET MVC I see quite basic entities, with simple CRUD methods.
But I\'m not sure about what to do with more advanced models. Let me give an

5条回答
  •  春和景丽
    2020-12-28 22:57

    You don't need to have too many things going on in a controller.
    Think of a controller as a class that determines what the user wants and what it should see in the end.

    What user wants is determined by the ASP.NET MVC engine automatically for you, with the help of the routes you defined in the Global.asax file. Then the controller should decide what view the user should see as a result of the request he/she made.

    So for your application things would go something like this :

    Global.asax

    routes.MapRoute("Cars", "cars/{id}/{action}",
        new { controller = "Cars", action = "Details", id = "" } );
    //This route should give you the URLs you listed on your question
    

    CarsController.cs

    public class CarsController : Controller {
    
        //this action will be called for URLs like "/cars/423"
        //or /cars/423/details
        public ActionResult Details(int id) {
             //You would most likely have a service or business logic layer
             //which handles talking to your DAL and returning the objects 
             //that are needed for presentation and likes
             Car car = SomeClass.GetCar(id);
             if (car == null) {
                 //if there's no car with the ID specified in the URL
                 //then show a view explaining that
                 return View("CarNotFound");
             }
             //if there's a car with that ID then return a view that
             //takes Car as its model and shows details about it
             return View(car);
        }
    
        //this action will be called for URLs like /cars/423/edit
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(int id) {
            //again get the car, show an edit form if it's available for editing
        }
    
        //this action will be called for URLs like /cars/423/edit too
        //but only when the request verb is POST
        [AcceptVerbs(HttpVerbs.Post), ActionName("Edit")]
        public ActionResult Save(int id) {
            //save the changes on the car, again using your business logic layer
            //you don't need the actual implementation of saving the car here
            //then either show a confirmation message with a view, 
            //saying the car was saved or redirect the user to the 
            //Details action with the id of the car they just edited
        }
    
    }
    

    So basically this is how you would set up your controller(s) for an application like that.

提交回复
热议问题