We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution
Learn MoreWell we’ve arrived at the last part of our series on ASP.NET MVC. In this post we’ll be looking at Views, ViewData, and HTML Helpers. We’ll be discussing how to call Views from Controllers and how to use HTML Helpers to create your markup.
Suppose we receive the following request; http://yourdomain.com/Task/Show/23. The request would map to the following controller.
1: public class TaskController : Controller
2: {
3: public ActionResult Show()
4: {
5: return View();
6: }
7: }
The call to View() will return a view to be displayed. This view is located YourProject\Views\Task\Index.aspx. If the view were called like View("TaskDetail") then it would use the view at YourProject\Views\Task\TaskDetail.aspx. That is all there is to calling a view from a controller.
Calling the view is the easy part but we still need to pass data to our view and build the HTML to display the content. Here is a basic shell for a view page
There is nothing new here except your page declaration inherits from the ViewPage class. The rest is just standard HTML markup. So what can we put in the view for content? Well, you can input code snippets using server tags just like you can in WebForms.
Again this is nothing really new. MVC introduces HTML Helpers that take the place of Server Controls and help you build out your HTML. For example lets create a link to another section of our application.
What this does is create the anchor markup for us and takes care of setting the href attribute properly based on the Routes we have defined for our application.
Now that you know how to create a view you will need to pass data from your controllers to your views. This is done very easily but adding your data to a key/value collection in the controller. public
1: class TaskController : Controller
2: {
3: public ActionResult Show()
4: {
5: ViewData["MyData"] = "Some data I want to pass"; return View();
6: }
7: }
Then in the view you can display it like this.
That pretty much wraps up this post and the ASP.NET MVC series.
You can check put all the other posts here:
Stay tuned for more great posts from Dev102.com by grabbing the RSS feed. You can also see more posts I have written on my blog or grab my RSS feed.
Tags :
ASP.NetASP.NET MVCControllerdataHTMLViewViews Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd
strike
Said on December 22, 2009 :
quite poor tut. Yes, I wanted something like “in a nutshell” … but not confusing and lackluster as this one…