C # MVC for a single page website?

As I understand it, C # MVC ASP.NET is that I have several subpages for different data.

For instance,

  • mysite.com/Home
  • mysite.com/Car
  • mysite.com/AboutMe

For this, I would have 3 models: Home, Car and AboutMe and 3 Controllers.

What if I would like to have a website on one page where you can simply scroll from top to bottom. How to do this with MVC? Can I make only 1 controller? If so, how can I get 3 models that I need from the controller?

+4
source share
3 answers

There are several ways to do this in MVC. You can visit this: link

You can use one ViewModel, which will contain your data HOme, Car, AboutMe.
You can also use partial views. Here I am going to explain to you using one viewmodel approach.

In your ViewModel:

public class SingleViewModel { public List<Home> ListHome {get; set;} public List<Car> ListCar {get; set;} public List<AboutMe> ListAboutMe {get; set;} } 

In the controller:

  public ActionResult Index() { //you need to populate your viewmodel with data from database SingleViewModel model=new SingleViewModel(); model.ListHome=GetHomeData().ToList(); model.ListCar=GetCarData().ToList(); model.AboutMe=GetAboutMeData().ToList(); //pass your model to view return View(model); } 

In view

 @model <Proj.Model.SingleViewModel> 

// now you can fill in the data from your model here //

+1
source

You can have a parent object representing the Model that will contain the objects for the page 1,2,3, and in your views you will refer to the fields from the model by simply specifying a standard link to the instance name of the parent object. You will also need 1 controller.

 public class PageModel // parent model { // page models public HomeModel HomeModel {get; set;} public CarModel CarModel {get; set;} public AboutMeModel AboutMeModel {get; set;} } 
+3
source

There are different solutions for this. In general, MVC is also good for single-page applications or landing pages.

But now to your quetion about look models. You can create an “aggregate” model containing all three models:

 public class MainViewModel { public HomeModel HomeModel {get; set;} public CarModel CarModel {get; set;} public AboutMeModel AboutMeModel {get; set;} } 

As a second solution, you can also add these models in the ViewBag to the controller action and access them in the view (then you will not need the MainViewModel).

  public ActionResult Index() { ViewBag.HomeModel = new HomeModel(); ViewBag.CarModel = new CarModel(); ViewBag.AboutMeModel = new AboutMeModel(); return View(); } 
+2
source

All Articles