Tag helpers are a new feature in MVC 6 and are similar to the old style HTML helper methods though they have a more HTML like syntax.
There’s plenty of good guides about how to use them around so I’m not going to rehash that here, instead, what I’m mostly interested in is their use for select lists.
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
The resulting list of Products is then passed through to the view from the controller.
[HttpGet]
public IActionResult Register()
{
List<Product> products = Common.GetProducts(_config.GetConnectionString("AzureConnection"));
ViewData["Products"] = products;
return View();
}
A select list in a form can then be populated with the product values.
<div class="clearfix"/>
<div class="col-lg-3 col-md-6 col-xs-12">
<div class="x_panel">
<div class="x_title">
<div class="clearfix"/>
</div>
<div class="x_content">
<h2>Register</h2>
<form asp-controller="Home" asp-action="Register" method="post" id="RegisterForm" data-toggle="validator" role="form">
<fieldset>
<div class="item form-group required field">
<div class="row">
<div class="col-md-4">
<label asp-for="ProductId" class="control-label"/>
</div>
<div class="col-md-8">
<select asp-for="ProductId" asp-items="@(new SelectList(ViewBag.Products, "ProductId", "ProductName"))" class="form-control" required>
<option selected="selected" value="" disabled>--Please Select--</option>
</select>
<div class="help-block with-errors"/></div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</fieldset>
</form>
</div>
</div>
</div>
In order to pass the select item text back in the form rather than the ID the easiest option is to just set the value to be the text as well.
<select asp-for="ProductId" asp-items="@(new SelectList(ViewBag.Products, "ProductName","ProductName"))" class="form-control" required>
<option selected="selected" value="" disabled>--Please Select--</option>
</select>
Another useful tag helper is the one for generating address links to controller actions.
<a href="@Url.Action("Edit", "Template")"></a>
It can also pass parameters through in the URL to the action.
<a href="@Url.Action("Edit", "Template", new { TemplateId = templateDetail.TemplateId })"></a>
0 Comments