Thursday, 26 December 2013

Usage of View in the ASP.NET MVC

In this article we are going to see the view in the MVC, whenever controller and there action is executed, the corresponding view is given as output to the browser. The view name is same as the action name. to create the view right click on the action and press the add view and select the Razor engine and click ok  Now the view is added in the corresponding controller folder under the views.

Return type of the action is the ActionResult , now we take a  Example of list a employee details in the view by creating a Employee collection and save the value to the ViewBag.

Why we have to store the value to the ViewBag ?
  If we want to pass the value from the controller action to the View then it should be done by the ViewBag, then the last line return type is View().

 Why always return View()?
     If we want to send the result as View of that action to the user then return View() should be called at the last line,because it maps to the default view of that action which is having the same name in the controller folder under the views.

how the execution is takes place ?
    when the users requests the action of the controller, then the each and every line in the action executes and the value which are need to be pass to the view is stored in ViewBag , then finally view of that action is return after the Render by replacing the value from the ViewBag.

For Razor we have to specify the @ for use the C# code and whenever a variable is used then specify the @ symbol, otherwise it is taken as string.

    ViewBag.Title is used for specify the Title page


public class HomeController : Controller
    {

        public ViewResult Sample()
        {
            ViewBag.Employees = new List<string>() { "Rajesh", "Suresh", "Ramu", "Siva"};           
            return View();
        }
}

@{
    ViewBag.Title = "Employee Records";
}

<h2>Employee Names</h2>
<ul>
@foreach (string empname in ViewBag.Employees)
{
    <li>@empname</li>
}
</ul> 



output:



From this article you can learn the usage of view in MVC and how the view is map to the controller and how the data is passed between the controller action and the view.

No comments:

Post a Comment