// MVC Controller action that returns a view
public IActionResult Index()
{
List<string> items = new List<string> { "Item 1", "Item 2", "Item 3" };
return View(items);
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
@model List<string>
<ul>
@foreach (var item in Model)
{
<li>@item</li>
}
</ul>
public class ProductController : Controller
{
public IActionResult Details(int id)
{
var product = ProductService.GetProductById(id);
return View(product);
}
}
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
[Route("products")]
public IActionResult Index()
{
// Action logic
}
public IActionResult Create([Bind("Name,Price")] Product product)
{
// Create the product using model binding
}
[HttpPost]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
// Process the valid product data
}
}
public class ProductController : Controller
{
private readonly IProductService _productService;
public ProductController(IProductService productService)
{
_productService = productService;
}
// Use _productService to interact with product data
}
[Authorize]
public IActionResult SecureAction()
{
// Action logic for authenticated users
}