Razor tags | .NET

 Razor is a view engine used in ASP.NET MVC to create dynamic web pages. It provides a compact and expressive syntax for embedding C# code within HTML markup. Here are some of the most commonly used Razor tags and constructs:


1. `@:`: Used for inline code execution without rendering a value. It's often used to execute code blocks within HTML markup.


   ```razor

   <p>@DateTime.Now</p>

   ```


2. `@model`: Specifies the model type for the view, allowing you to strongly type the view to a specific model class.


   ```razor

   @model YourNamespace.YourModel

   ```


3. `@{ }`: Used for code blocks within Razor views. You can place C# code within these code blocks.


   ```razor

   @{

       var userName = "John";

       var age = 30;

   }

   ```


4. `@if { }`, `@else if { }`, `@else { }`: Conditional statements for rendering HTML based on conditions.


   ```razor

   @if (condition)

   {

       <p>Condition is true</p>

   }

   else

   {

       <p>Condition is false</p>

   }

   ```


5. `@foreach { }`: Used for looping through collections to generate repeated HTML elements.


   ```razor

   <ul>

       @foreach (var item in Model.Items)

       {

           <li>@item.Name</li>

       }

   </ul>

   ```


6. `@Html.ActionLink()`: Generates hyperlinks to controller actions, allowing for easy navigation within the application.


   ```razor

   @Html.ActionLink("Home", "Index", "Home")

   ```


7. `@Html.Partial()`: Renders a partial view within the main view. Useful for reusing components.


   ```razor

   @Html.Partial("_PartialViewName")

   ```


8. `@Html.RenderPartial()`: Similar to `@Html.Partial()`, but it directly renders the partial view.


   ```razor

   @Html.RenderPartial("_PartialViewName")

   ```


9. `@Html.TextBoxFor()`, `@Html.DropDownListFor()`, `@Html.TextAreaFor()`: Generates form controls for model properties.


   ```razor

   @Html.TextBoxFor(model => model.UserName)

   ```


10. `@Html.ValidationSummary()`, `@Html.ValidationMessageFor()`: Renders validation error messages for form fields.


    ```razor

    @Html.ValidationSummary()

    @Html.ValidationMessageFor(model => model.UserName)

    ```


11. `@section { }`: Defines named sections in a layout view that can be overridden by child views.


    ```razor

    @section Scripts {

        <script src="~/Scripts/custom.js"></script>

    }

    ```


These are some of the most commonly used Razor tags and constructs in ASP.NET MVC. Razor provides a powerful and concise way to mix HTML markup with C# code, making it easier to create dynamic and data-driven web pages.

Dropdown

In ASP.NET MVC, there isn't a specific `@dropdown` tag in Razor. However, you can create dropdown lists (HTML `<select>` elements) in Razor views using standard HTML elements and Razor syntax. Here's how you can create a dropdown list in a Razor view:


```razor

@Html.DropDownListFor(

    model => model.SelectedOption, // The model property to bind the selected value to

    new SelectList(Model.Options, "Value", "Text"), // The list of options (e.g., IEnumerable<SelectListItem>)

    "Select an option", // Placeholder text for the dropdown

    new { @class = "form-control" } // HTML attributes for styling or JavaScript purposes

)

```


Here's what each part of this code does:


- `@Html.DropDownListFor`: This is a Razor helper method that generates a dropdown list. It's used to create the `<select>` element.


- `model => model.SelectedOption`: This part specifies the model property that will hold the selected value when the user makes a selection.


- `new SelectList(Model.Options, "Value", "Text")`: Here, you provide a list of options, typically an `IEnumerable<SelectListItem>`, with properties for the option's value and text. In this example, `Value` and `Text` represent properties on each `SelectListItem` in the list.


- `"Select an option"`: This is the text that will be displayed as the default option in the dropdown. It serves as a placeholder.


- `new { @class = "form-control" }`: You can use this part to add HTML attributes to the dropdown, such as a CSS class for styling. In this case, we've added the `form-control` class, which is a common Bootstrap class for styling form elements.


This code generates an HTML `<select>` element with `<option>` elements based on the `Model.Options` collection, and it binds the selected value to the `model.SelectedOption` property when the user makes a selection. You can customize this code to fit your specific model and requirements.


Remember to adjust the model property and the collection of options (`Model.Options`) based on your application's data and needs.


To send dropdown data from a controller action to a Razor view in ASP.NET MVC, you can pass the data as part of the model. Here's how you can do it:


1.Define a ViewModel: Create a view model class that represents the data you want to send to the view. This view model should include a property to hold the data for the dropdown.


   ```csharp

   public class MyViewModel

   {

       public IEnumerable<SelectListItem> DropdownData { get; set; }

       public int SelectedOption { get; set; }

   }

   ```


   In this example, `DropdownData` is an `IEnumerable<SelectListItem>` property to hold the dropdown options, and `SelectedOption` is a property to hold the selected value.


2. Populate Dropdown Data in the Action: In your controller action, create an instance of the view model, populate the `DropdownData` property with the dropdown options, and return the view with the view model.


   ```csharp

   public ActionResult MyAction()

   {

       var viewModel = new MyViewModel

       {

           // Populate DropdownData with your data source

           DropdownData = GetDropdownOptions(),

           // Optionally, set a default selected value

           SelectedOption = 2

       };


       return View(viewModel);

   }


   private IEnumerable<SelectListItem> GetDropdownOptions()

   {

       // Retrieve and format your dropdown options

       var options = new List<SelectListItem>

       {

           new SelectListItem { Value = "1", Text = "Option 1" },

           new SelectListItem { Value = "2", Text = "Option 2" },

           new SelectListItem { Value = "3", Text = "Option 3" }

       };


       return options;

   }

   ```


   In this example, `GetDropdownOptions` is a method that retrieves and formats the dropdown options. You can replace it with your own data retrieval logic.


3. Create a Razor View: Create a Razor view (e.g., `MyView.cshtml`) that corresponds to your action. In the view, use the `@Html.DropDownListFor` helper to render the dropdown using the data from the model.


   ```razor

   @model YourNamespace.MyViewModel


   @Html.DropDownListFor(

       model => model.SelectedOption,

       Model.DropdownData,

       "Select an option",

       new { @class = "form-control" }

   )

   ```


   This code will generate a dropdown list using the `DropdownData` property from the model. The `SelectedOption` property will hold the selected value when the form is submitted.


4. Handle POST Requests (if applicable): If your view includes a form that submits data back to the server, you'll need to handle the POST request in your controller to process the selected option.


   ```csharp

   [HttpPost]

   public ActionResult MyAction(MyViewModel viewModel)

   {

       // Process the selected option (viewModel.SelectedOption)

       // ...

       return View(viewModel); // Optionally, return the view with updated data

   }

   ```


   In this `HttpPost` action, you can access the selected option via `viewModel.SelectedOption` and perform any necessary processing.


With these steps, you can send dropdown data from a controller action to a Razor view and render a dropdown list with options populated from the controller.




Comments