I have a view that shows a single item with all of its fields. But I'm getting confused trying to figure out how to allow one specific field ("Status") to be updated from this view, without necessarily going into a whole other "edit" view first.
How do I http-post to the same action (Details) but saving only the "Status" field, without saving all of the other properties which are part of the view model (for display only)? Do I need a separate view model just for the Status? New to ASP.NET MVC and getting confused.
public string FirstName { get; set; }
public string LastName { get; set; }
public string Birthdate{ get; set; }
public string Status { get; set; }
//etc.
<div>
@Html.DisplayFor(model => model.FirstName)
@Html.DisplayFor(model => model.LastName)
@Html.DisplayFor(model => model.Birthdate)
//etc.
</div>
<div>
@TextBoxFor(model => model.Status)
<button type="submit" value="Save Status" />
</div>
[HttpGet]
public ActionResult Details(int id)
{
var person = personRepo.GetById(id);
var vm = BuildPersonDetailsViewModel(person);
return View(vm);
}
[HttpPost]
public ActionResult Details(PersonDetailsViewModel vm)
{
var person = personRepo.GetById(vm.PersonID);
person.Status = vm.Status;
personRepo.Update(person);
}
So I solved this by ensuring that the primary key field PersonID is included in the View. I didn't think I needed it originally because it started off as a read-only Details view, and PersonID wasn't needed to be displayed. But when posting data back, I needed to add it as a hidden field, so it could be passed to the controller on HttpPost. Then it can be used to locate and update the record in the database.
Furthermore, I added another method in the repository to allow for updating of just the "Status" field, since that's the only value being updated. If I use the sample code above, my solution looks something like this:
public int PersonID { get; set; }
public string Status { get; set; }
public string FirstName { get; set; }
//etc.
@Html.HiddenFor(model => model.PersonID)
@Html.DisplayFor(model => model.FirstName)
//etc. (all the display fields)
@TextBoxFor(model => model.Status)
<button type="submit" value="Save Status" />
[HttpPost]
public ActionResult Details(PersonDetailsViewModel vm)
{
personRepo.UpdateStatus(vm.PersonID, vm.Status);
}