开发者

asp.net mvc and duplication

I am finding the asp.net mvc framework is leading me towards a fair bit of duplication. Maybe I just don't know of the correct way to do things, so I will list some of the areas and maybe someone can suggest the correct approach:

Controller methods that do not accept generic parameters. I have multiple classes, such as:

class A
class B : A
cla开发者_开发问答ss C : A
class D : A

and controller methods:

EditB(B obj)
EditC(C obj)
EditD(D obj)

All controllers do exactly the same thing, but I am assuming that 1. I can't have a generic controller parameter, and 2. the model binder will only bind to class A if I do:

EditA(A obj)

The next problem I have is with partials. To get model binding to work easily, I use methods such as:

Html.TextboxFor(m => m.blah.blahID)

but when a partial is shared between multiple views that only have m.blah in common, I do:

RenderPartial("BlahPartial", m.blah);

The problem is that now I would assume that using

Html.TextboxFor(m => m.blahID) 

inside the partial will not give me what I want as it is missing the blah.

Finally, in controller methods, I find it difficult to extract common algorithms into invidiual methods as:

if (a)

return ActionResult("Blah");

else 

return ActionResult("Home");

(or RedirectToAction or return View("Home") etc.)

seem diffuclt to put in private methods as I cannot return those things in anything other then the original controller.


I'm not sure exactly if I can put you on the right track as your question is pretty generic, but I think that you'll likely have to have separate controller actions per model. That doesn't mean that you can't share code. One way to do that would be to have a common base controller from which each specific controller derives. The code common to all controllers/models can be refactored back to the base controller.

As far as partials go, you can provide the prefix via ViewData -- see http://davybrion.com/blog/2011/01/prefixing-input-elements-of-partial-views-with-asp-net-mvc/

I'm not sure why you think that you can't easily have private methods. It's not difficult to have a private method that returns a particular model or uses a particular view by name.

private ActionResult RedirectOnSuccess<T>( T model, string action ) where T : IBaseModel
{
    if (model.IsValid())
    {
        // save to database, etc.
        return RedirectToAction( action );
    }
    return View( model ); // will re-render the view corresponding to the called action
}

Then call it as

public ActionResult Edit( SpecificModel model )
{
   return RedirectOnSuccess( model, "index" );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜