Create generic method to populate (load) Model in ASP.Net MVC

nauna
 
on Aug 25, 2021 10:43 PM
477 Views

Hello,

I have create and edit method in both method i have to write similar code to load my form model and dropdown list data

how to create generic method to load form data in method and call that method in the CreateMovies and Edit method

this should be generic method which returns viewmodel and pass to return view()

public ActionResult CreateMovies()
{
    var Listgenre = context.Genres.ToList();
    var ViewModel = new Create_Movie_Model()
            {
                Movies = new Movie(),
                Genres = Listgenre
            };
    return View("CreateMovies", ViewModel);
}

public ActionResult Edit( int id)
{
    Movie m = context.Movies.FirstOrDefault(u => u.Id == id);
    if (m != null)
    {
        var Listgenre = context.Genres.ToList();
        var ViewModel = new Create_Movie_Model()
                {
                    Movies = m,
                    Genres = Listgenre
                };

        return View("CreateMovies", ViewModel);
    }
    else
    {
        return HttpNotFound();
    }
}

 

var Listgenre = context.Genres.ToList();
var ViewModel = new Create_Movie_Model()
{
     Movies = new Movie(),
    Genres = Listgenre
};

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 26, 2021 04:16 AM

Hi nauna,

Refer below modified code.

Controller

public ActionResult CreateMovies()
{
    Create_Movie_Model ViewModel = GetCreateMovieModel();
    return View("CreateMovies", ViewModel);
}

public ActionResult Edit(int id)
{
    Movie m = context.Movies.FirstOrDefault(u => u.Id == id);
    if (m != null)
    {
        Create_Movie_Model ViewModel = GetCreateMovieModel();
        ViewModel.Movies = m;
        return View("CreateMovies", ViewModel);
    }
    else
    {
        return HttpNotFound();
    }
}

public Create_Movie_Model GetCreateMovieModel()
{
    var Listgenre = context.Genres.ToList();
    Create_Movie_Model ViewModel = new Create_Movie_Model()
    {
        Movies = new Movie(),
        Genres = Listgenre
    };

    return ViewModel;
}