In ASP.NET MVC, a View is responsible for rendering the user interface (UI) and displaying data to the user. Views are typically written using Razor syntax, which allows you to embed C# code within HTML. Below is a step-by-step guide on how to create a view in ASP.NET MVC.
Step 1: Create a Controller
Before creating a view, you need a controller to handle the request and pass data to the view. Here's an example of a simple controller:
public class HomeController : Controller
{
public ActionResult Index()
{
// Pass data to the view
ViewBag.Message = `Welcome to ASP.NET MVC!`;
return View();
}
}
In this example, the Index action method returns a view and passes a message using ViewBag.
Step 2: Add a View
To create a view for the Index action, follow these steps:
- Right-click on the
Viewsfolder in your project. - Select Add > New Folder and name it
Home(to match the controller name). - Right-click on the
Homefolder, select Add > View. - Name the view
Index.cshtml(to match the action name).
Step 3: Write the View Code
Once the view is created, you can write the HTML and Razor code to display the data. Here's an example of the Index.cshtml view:
@{
ViewBag.Title = `Home Page`;
}
<h2>@ViewBag.Message</h2>
<p>This is the home page of the ASP.NET MVC application.</p>
In this example:
@ViewBag.Titlesets the title of the page.@ViewBag.Messagedisplays the message passed from the controller.
Step 4: Run the Application
After creating the controller and view, run the application. Navigate to the Home/Index URL, and you should see the message `Welcome to ASP.NET MVC!` displayed on the page.
Key Points to Remember
- Views are stored in the
Viewsfolder, organized by controller name. - Razor syntax (
@) is used to embed C# code within HTML. - Use
ViewBagor a strongly-typed model to pass data from the controller to the view.
By following these steps, you can easily create and manage views in your ASP.NET MVC application.
