0

I have a view, which simply does a foreach loop on a IEnumerable passed in the viewmodel, I have a way for people to select these entities on the list (apply a class to them to highlight), and this currently works for some clientside printing through jquery. Is there a way I can get these entities (staff) which have the highlight class and push them back as a model to the controller?

I have tried to use html.hiddenfor and just putting all the staff in there and making a form, with asp-action of my function on the controller and just a submit button, this did not work

the controller contains

public IActionResult StaffSelectionAction(StaffIndexModel model)
        {
            //things to do to process the selected staff
            foreach (Staff staff in model.staff){
                //Do stuff
            }
            return RedirectToAction("Index");
        }

the view contains

<form asp-action="StaffSelectionAction">
    @Html.HiddenFor(b => b.staff)
    <input type="submit" value="Process Staff" class="btn btn-default" asp-action="StaffSelectionAction"/>
</form>

model contains

public IEnumerable<Staff> staff { get; set; }

Edit: spelling mistake in code

  • Aren't you trying to do something similar to this [question](https://stackoverflow.com/questions/18824638/select-multiple-value-in-dropdownlist-using-asp-net-and-c-sharp)? – Pati K Feb 05 '19 at 12:56

1 Answers1

0

There are a few ways to handle this.

One way is to create an helper class, extending the Staff model and adding a 'selectable' attribute for it. Something like:

public class SelectableStaff : Staff
{
    public bool Selected {get; set;}
}

Then in your view:

@Html.CheckBoxFor(m => m.Selected)

Using model binding, binding back to the controller with type SelectableStaff should then give you the selected values where you can do something like:

   foreach (SelectableStaff staff in model.staff.Where(x => x.Selected)){
                //Do stuff
   }

You can get it back to Staff easily enough using linq and contains. Alternatively, you can also use @Html.Checkbox("myfriendlyname"), then include a FormCollection in the controller and pull the variable out of it. Personally, I think the model binding is less error prone.

  • The issue I am having is I can't seem to get the model back from the page to be able to do something with it – Martyn Price Feb 05 '19 at 13:24
  • Sorry for the late reply. The best way to do this is a combination of Html.EditorFor(x => x.YourAttribute), Html.TextBoxFor(...), and so on. There's quite a few of them that exist. This relies on the top of your HTML file being @model YourTypeHere Then, when you post back, you can use Html.BeginForm(..) with the using clause to setup the form post back, the argument your controller would receive would be of the type of object you used to reference the Html.EditorFor/etc stuff. – TheDarkTrumpet Feb 11 '19 at 19:05