Consider this model and viewmodel:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
public class PersonViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
A form to edit just the e-mail:
<form asp-action="UpdateEmail">
<input type="hidden" asp-for="Id" />
<label asp-for="Email"></label>
<input asp-for="Email" />
<button type="submit">Update e-mail address</button>
</form>
And the UpdateEmail()
POST controller method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UpdateEmail(int id, [Bind("Id,Email")] Person person)
{
if (id != person.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
db.Update(person);
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
// ... stuff
}
return RedirectToAction("Details", new { id = person.Id });
}
return View(auto.Map<PersonViewModel>(person));
}
It is my experience that in this case, all other properties besides Email
will be overwritten by NULL
values. Do I really have to add them as hidden fields in the form? If so, then what is the point of using [Bind("Id,Email")]
?