Friday, August 26, 2011

I guess the whole situation begs for a refactoring.

Which lines below seem not to belong in a controller action?

[HttpPost]

public ActionResult Edit(FooModel fooModel, Guid id)

{

   Foo foo = ProgramRepository.GetById(id);

   foo.Name = fooModel.Foo.Name;

   foo.Description = fooModel.Foo.Description;

   fooModel.Foo = foo;

   fooModel.Save();

   return RedirectToAction("Index");

}

 
 

The lines in white here are the lines that should be kept.

[HttpPost]

public ActionResult Edit(FooModel fooModel, Guid id)

{

   Foo foo = ProgramRepository.GetById(id);

   foo.Name = fooModel.Foo.Name;

   foo.Description = fooModel.Foo.Description;


   fooModel.Foo = foo;

   fooModel.Save();

   return RedirectToAction("Index");

}

 
 

So why the extra lines. In this case FooModel has numerous get-setters including a wrapper for the domain object itself like so:

public string Name { get; set; }

public string Description { get; set; }

public bool IsActive { get; set; }

public bool IsOfBar { get; set; }

public Foo Foo { get; set; }

 
 

Foo itself has these get-setters:

public string Name { get; set; }

public string Description { get; set; }

public bool IsActive { get; set; }

public bool IsOfBar { get; set; }

 
 

When editing Foo, the View contains two checkboxes for IsActive and IsOfBar and these get mapped to the wrapper upon model binding. Then the .Save() method will assign the values for the checkboxes to the IsActive and IsOfBar on the Foo inside FooModel and ultimately "Save" the Foo as the method name suggests. This is not my code. It is Mike's. But, I had to get saving working for Name and Description. In keeping with the checkboxes, I wrote Razor form fields like so:

@Html.EditorFor(model => model.Name)

 
 

Instead of like so:

@Html.EditorFor(model => model.Foo.Name)

 
 

Instead of like so:

Unfortunately, this sabotaged our jQuery sanity checking that is made to work with the fields on domain objects, so I ultimately had to use the later means above. Komali and I looked into this yesterday. It was her last day. I guess the whole situation begs for a refactoring.

No comments:

Post a Comment