Firstly, I am teaching myself ASP.NET MVC using ASP.NET Core 2.1 with EF Core 2.1, so I'm rather noob at this.
I am trying to change a Create View, to accept an optional parameter for a ClientID. The idea is to allow selecting from all clients if no ID is supplied, but if supplied, force the form input for the client to the given value.
I am having trouble getting GET to recognize there is a parameter, unless the parameter is specifically int? id . If i change it to this, then when submitted to POST an exception is raised for a duplicate ID.
All Controllers and Views were scaffolded, only the GET method shown has been changed.
Controller Create GET Method:
// GET: ServiceRequest/Create/1
public IActionResult Create(int? clientId)
{
ViewData["ClientData"] = new SelectList(_context.Clients, "ID", "FullName");
if (clientId != null ) {
if (_context.Clients.Find(clientId) == null) {
return NotFound();
}
ViewData["ClientID"] = clientId;
ViewData["ClientName"] = _context.Clients.Find(clientId).FullName;
}
ServiceRequest request = new ServiceRequest();
request.Deadline = DateTime.Today;
request.Status = Models.Status.DRAFT;
return View(request);
}
Create View:
@model AskewServices.Models.ServiceRequest
@{
ViewData["Title"] = "Open Service Request";
}
<h2>@ViewData["Title"]</h2>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Deadline" class="control-label"> </label>
<input asp-for="Deadline" class="form-control" />
<span asp-validation-for="Deadline" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Status" class="control-label"></label>
<select disabled asp-for="Status" class="form-control">
<option [email protected]>Draft</option>
</select>
<span asp-validation-for="Status" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Client</label>
@if (ViewData.ContainsKey("ClientID")) {
<select disabled asp-for="ClientID" class="form-control">
<option value=@ViewData["ClientID"]>@ViewData["ClientName"]</option>
</select>
} else {
<select asp-for="ClientID" class="form-control" asp-items="ViewBag.ClientData"></select>
}
</div>
<div class="form-group">
<input type="submit" value="Open" class="btn btn-warning" />
<input type="reset" value="Reset" class="btn btn-info" />
</div>
</form>
</div>
</div>
Routes:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "OpenServiceRequest",
template: "{controller=ServiceRequest}/{action=Create}/{clientId?}");
});
Thoughts: Parameters not being specified the right way, or a problem with Routing (it might not be seeing the ServiceRequest Create route)?