Exercise Solutions: Razor Views¶
Line numbers are for reference. They may not match your code exactly.
Expanding our Events Schedule¶
Update the
Events/Add.cshtml
template with a new field for a user to submit an event description.
<h1>Add Event</h1>
<form method="post">
<label for="name">Name</label>
<input name="name" type="text" />
<label for="desc">Description</label>
<input name="desc" />
<input type="submit" value="Add Event" />
</form>
Back in
EventsController.cs
, add the description parameter to theNewEvent
action method and within the method, add the new event key/value pair to theEvents
dictionary.
[HttpPost]
[Route("Events/Add")]
public IActionResult NewEvent(string name, string desc)
{
Events.Add(name, desc);
return Redirect("/Events");
}
Now to
Events/Index.cshtml
. Replace theul
with atable
to display event names and descriptions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // inside the "else" block
<table>
<tr>
<th>
Name
</th>
<th>
Description
</th>
</tr>
@foreach (KeyValuePair<string, string> evt in ViewBag.events)
{
<tr>
<td>@evt.Key</td>
<td>@evt.Value</td>
</tr>
}
</table>
|
Lastly, modify
_Layout.cshtml
to display links for the Coding Events app (onlyEvents/Index
andEvents/Add
for now).
1 2 3 4 5 6 7 8 9 10 11 | <header>
<!-- html code -->
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Events" asp-action="Add">Add</a>
</li>
</ul>
</div>
<!-- more html -->
</header>
|