This is a migrated thread and some comments may be shown as answers.

Generic Grid Controller Methods for multiple models

0 Answers 185 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Greg
Top achievements
Rank 1
Greg asked on 05 Apr 2013, 12:32 PM
I'm using the Table Per Concrete type where I have all my models inherit from one base class which has common properties. Since the Get, Insert, Update, and Delete methods do the same thing for each model I'm using, I want to make these methods reusable for each of these models.

Here is the code that I currently have:

PhoenixDB ctx = new PhoenixDB();

public ActionResult Index()
{
return View();
}

public ActionResult Get([DataSourceRequest] DataSourceRequest request)
{
return Json(GetViewModels().ToDataSourceResult(request));
}

public ActionResult Update([DataSourceRequest] DataSourceRequest request, Parameter parameter)
{
var parameterToUpdate = ctx.Parameter.First(param => param.ParameterID == parameter.ParameterID);
TryUpdateModel(parameterToUpdate);

ctx.SaveChanges();

return Json(ModelState.ToDataSourceResult());
}

public ActionResult Insert([DataSourceRequest] DataSourceRequest request, Parameter parameterToAdd)
{
if (ModelState.IsValid)
{
ctx.Parameter.Add(parameterToAdd);
ctx.SaveChanges();
}

return Json(new[] { parameterToAdd }.ToDataSourceResult(request));
}

public ActionResult Delete([DataSourceRequest] DataSourceRequest request, Parameter parameter)
{
var parameterToDelete = ctx.Parameter.First(param => param.ParameterID == parameter.ParameterID);

if (parameterToDelete != null)
{
ctx.Parameter.Remove(parameterToDelete);
ctx.SaveChanges();
}

return Json(new[] { parameterToDelete }.ToDataSourceResult(request));
}

private IQueryable<Parameter> GetViewModels()
{
return (from parameter in ctx.Parameter select parameter);
}

Here is something I would like to do to make it generic, but not sure how:

public ActionResult Update([DataSourceRequest] DataSourceRequest request, Base base)
{
var baseToUpdate = ctx.Base.First(param => param.ParameterID == base.ParameterID);
TryUpdateModel(baseToUpdate);

ctx.SaveChanges();

return Json(ModelState.ToDataSourceResult());
}

Any help with this would be greatly appreciated.

No answers yet. Maybe you can help?

Tags
Grid
Asked by
Greg
Top achievements
Rank 1
Share this question
or