If the asp-for tag sets the name automatically, why does it not work if I remove the name tag so as not to set it manually?
Because you are not following standard MVC Core patterns and practices. I strongly recommend going through the tutorial in my first post which covers many basic concepts. I also recommend the data access tutorial. There is a lot of great information in these tutorials.
The following code sample is a minimalistic example using a Model, View, and Controller with standard model validation.
namespace MvcDemo.Controllers
{
public class FromViewModel
{
[Required]
public string Name { get; set; }
}
public class FormController : Controller
{
private readonly ILogger<FormController> _logger;
public FormController(ILogger<FormController> logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(FromViewModel model)
{
_logger.LogInformation(model.Name);
return View(model);
}
}
}
Markup
@model MvcDemo.Controllers.FromViewModel
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<h4>FromViewModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Index">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>