Greetings all,
Is it possible to use the BindAttribute (to prevent overposting) in an HTTP post with a nested class? It seems like I'm just missing something obvious. My nested class is always "empty". I am using ASP.NET Core 1.1.0. BTW everything binds fine without the BindAttrbute.
What I've Tried
[HttpPost, ValidateAntiForgeryToken] public IActionResult Index(int id, [Bind("Id", "FirstName", "LastName", "Birthday")] PersonViewModel model) [HttpPost, ValidateAntiForgeryToken] public IActionResult Index(int id, [Bind("Id", "FirstName", "LastName", "Birthday", Prefix = "Person")] PersonViewModel model) [HttpPost, ValidateAntiForgeryToken] public IActionResult Index(int id, [Bind("Person.Id", "Person.FirstName", "Person.LastName", "Person.Birthday")] PersonViewModel model) [HttpPost, ValidateAntiForgeryToken] public IActionResult Index(int id, [Bind("Person.Id", "Person.FirstName", "Person.LastName", "Person.Birthday", Prefix = "Person")] PersonViewModel model)
Sample Model
public class Person { public int Id { get; set; } [Required] public string FirstName { get; set; } [Required] public string LastName { get; set; } [Required, DataType(DataType.Date)] public DateTime Birthday { get; set; } }
Sample ViewModel
public class PersonViewModel { public Person Person { get; set; } = new Person(); }
Sample Controller
public class PersonController : Controller { private static Person _person = new Person { Id = 1, FirstName = "John", LastName = "Smith", Birthday = DateTime.Now.AddYears(-30) }; public IActionResult Index() { return View(new PersonViewModel { Person = _person }); } [HttpPost, ValidateAntiForgeryToken] // See variations above of what I have tried. public IActionResult Index(int id, [Bind("Id", "FirstName", "LastName", "Birthday", Prefix = "Person")] PersonViewModel model) { if (id != model.Person.Id) return NotFound(); if (ModelState.IsValid) { _person = model.Person; return RedirectToAction("Index"); } return View(model); }
Sample View
@model PersonViewModel<form asp-action="Index" asp-route-id="@Model.Person.Id"><div class="form-horizontal"><div asp-validation-summary="All" class="text-danger"></div><input type="hidden" asp-for="Person.Id" /><div class="form-group"><label asp-for="Person.FirstName" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Person.FirstName" class="form-control" /></div></div><div class="form-group"><label asp-for="Person.LastName" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Person.LastName" class="form-control" /></div></div><div class="form-group"><label asp-for="Person.Birthday" class="col-md-2 control-label"></label><div class="col-md-10"><input asp-for="Person.Birthday" class="form-control" /></div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="Save" class="btn btn-primary" /></div></div></div></form>