Question

I'm working on a sort of a CMS/Wiki application to help me experiment with the new Asp.Net MVC framework, and I'm trying to wrap my head around some of the code organization.

Right now, I have three views that cover displaying an article: Index, Edit, and Rename. All three views display the contents of the current page, or placeholder content stating that the page does not exist.

This is currently accomplished with the following code in the action method for each view:

MyPage myPage = null;

if (!string.IsNullOrEmpty(pageName)) {
    myPage = mRepository.GetMyPage(pageName);
}

//Page does not exist.
if (myPage != null) {
    ViewData["pageContent"] = myPage.GetParsedSource(new PageState());
    ViewData["pageSource"] = myPage.Source;
    ViewData["title"] = myPage.Title;
}
else {
    ViewData["title"] = pageName;
    ViewData["pageContent"] = "Page does not exist, feel free to create it!";
    ViewData["pageSource"] = "";
}

ViewData["pageName"] = pageName;

My question is, where should this logic actually go?

1) The Controller (as it is now), which requires the above code to be replicated across action methods?
2) The Model, defaulting values for pageSource to the verbiage shown above? This would have the downside of moving display text into the model.
3) The View, using a null coalescing operator to convert null ViewData entries to their defaults?
4) In the Views, but add additional controllers to handle cases where the pageName does not exist.


EDIT: Hopefully this should clarify things a little. The flow of the application is as follows: When the user enters a URL (i.e. /pages/page_title), they arrive at a screen which displays the content of the article, along with hyperlinks labeled "edit" and "rename."

Clicking edit displays a page which contains the article content, as well as form controls to edit the article's source.

Clicking rename displays a page which contains the article content, as well as form controls to edit the article's name.

Was it helpful?

Solution

I would have several actions:

  • Lookup
  • Display
  • Create
  • Edit
  • Rename

In your default Lookup controller action (which gets hit when the user asks for, say, "/wiki/article-title"), you can redirect (RedirectToAction()) to the appropriate action as necessary. That encapsulates your Create logic into its own controller, and can also be called directly (RESTful). Same with the others. That also allows you to keep your views very, very stupid (always a good thing).

OTHER TIPS

I would keep it in the controller but extract it out so that you don't have to replicate the code in each of the actions.

Maybe set some defaults in the controller's constructor and then have a separate private method (ie. not an action method) that takes your MyPage object and sets the viewdata that is shared between your actions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top