View a non-passing Ienumerable of Model

Edit: removed partial view to simplify work. Now I just need to find out why The View doesn't post the values

  • ViewModelProspectUsers

    public class ViewModelProspectUsers { public int Id { get; set; } public string User { get; set; } public IEnumerable<ViewModelProspectSelect> Prospects { get; set; } } 
  • ViewModelProspectSelect

     public class ViewModelProspectSelect { public int ProspectID { get; set; } public string Name { get; set; } public bool IsSelected { get; set; } } 
  • View

     @model OG.ModelView.ViewModelProspectUsers @using (Html.BeginForm()) { @Html.HiddenFor(model => model.Id) <h5>Please Select Prospects you wish to assign to this User.</h5> 

----- HERE where partial is used, these values ​​are not sent to the [Post] method ------

----------------------------------------- However, they populate just fine ---- ------------------------------------

  @foreach (var item in Model.Prospects) { @Html.HiddenFor(x => item.ProspectID) @Html.DisplayFor(x => item.Name) @Html.EditorFor(x => item.IsSelected) } 

  @*@Html.Partial("_ShowProspectCheckedForUser", Model.Prospects)*@ @*@Html.Partial("_ShowProspectCheckedForuser", new OG.ModelView.ViewModelProspectSelect())*@ <input type="submit" value="Save changes" /> @Html.ActionLink("Cancel", "Index") } 
  • Message

      [HttpPost] public ActionResult UsersInProspect(ViewModelProspectUsers viewModel) 

If I were looking at viewModel.Prospects(m=>m.isSelected) // <- this Null value should not be

My viewmodel Variableis shows data, but not for Ienumerable.

+1
parameter-passing c # asp.net-mvc razor partial-views
source share
1 answer

When working with objects of the list type, you must refer to them using array notation so that the field names are generated in such a way that the model node can analyze them, i.e.

 for (var i = 0; i < Model.Count(); i++) { @Html.LabelFor(m => Model[i].SomeProperty) @Html.EditorFor(m => Model[i].SomeProperty) } 

In your scenario, you would be better off using the view model to contain your list and adding the Selected property to the elements so you can keep track of which ones were or were not selected.

 public class ViewModelProspects { public List<ViewModelProspectSelect> Prospects { get; set; } } public class ViewModelProspectSelect { // Whatever else you have public bool Selected { get; set; } } 

Then, in your opinion:

 @model ViewModelProspects @using (Html.BeginForm()) { for (var i = 0; i < Model.Prospects.Count(); i++) { <label> @Html.HiddenFor(m => Model.Prospects[i].Id) @Html.CheckboxFor(m => Model.Prospects[i].Selected, true) @Model.Prospects[i].Name </label> } } 

And finally, change the signature of your action:

 [HttpPost] public ActionResult UsersInProspect(ViewModelProspects model) 

Then you can easily get a list of selected identifiers within the action with:

 var selectedIds = model.Prospects.Where(m => m.Selected).Select(m => m.Id) 
+1
source share

All Articles