Today I teach some of my junior programmer on how to work with ASP.NET MVC, first question they ask once they see the sample of MVC from standard Visual Studio 2010 template is “what if I want only return Hello World as the output?”, coincidently this question is the same question always being asked to me by MVC newbie.
MVC concept segregates layer of development into Model, View and Controller. Most of time developer effort will be on Controller and View and these 2 layers have a mutual relationship, because Controller will handle all business logic and/or data processing while View is meant for UI handling purpose. Sometime as programmer, we will need to test our business logic function has proper output or not, and the output normally just simple object or value. Build a different view to render the output seems too many effort to do and will add more “to-be-deleted” file on our solution, hence question on how to send simple output directly from Controller is really logical.
Okay, back to the issue, what is the solution? ASP.NET MVC have a class “ContentResult” to accomodate this problem. Code should be like below:
1: public class HomeController : Controller
3: public ActionResult Index()
5: String ret = "Hello World!";
7: //-- build return string here
8: return Content(ret);
Have a nice MVC Controller test !!!