0

I have the following code. The model is an Asset. However, what I want is to assign a user for each Asset in View Model through @Html.DropDownListFor(model => model.UserFromTable, new SelectList(Model.UsersFromTable, "UserName", "UserName")).

The thing is that I tried appropriate SelectList<> etc., but I don't know how to assign users from the dropdownlist in users column to assets in ViewModel. Another thing is that I don't receive my selection in ViewModel after Post. I can pass there some checkbox values but not the selections from the above dropdownlist.

I read some posts on stackoverflow and found out that some similar tasks require foreach. There is already one foreach loop in the code. I believe I should work on var item in Model.Assets somehow. I also have a separate CRUD Edit cshtml page for editing one single Asset but I want to save changes in user dropdownlist to all Assets on the current page.

Is it possible and how can I do it?

@Html.Partial("AssetsFiltering", Model.AssetsFilteringVM)
@foreach (var item in Model.Assets)
{
    <tr class="data-rows">
        <td>@Html.Span(item.Id)</td>
        ....
        <td>                       
            @Html.DropDownListFor(model => model.UserFromTable, new SelectList(Model.UsersFromTable, "UserName", "UserName"))
        </td>
matny
  • 1
  • How does your view model class definition looks like ? Are you using same view model as the parameter of your http post action method ? – Shyju Apr 03 '18 at 14:57
  • use ViewData to assign values to your dropdown list and name the dropdown list the same name as the property that will contain the selected value on your POST method – King of the North Apr 03 '18 at 16:03
  • But ViewModel contains public IEnumerable Assets { get; set; } and public IEnumerable UsersFromTable { get; set; }. How to bind the values from DropDownList to IEnumerable Assets through Post action? – matny Apr 04 '18 at 12:32
  • Finally I found the answer : @for(int i=0; i < Model.Assets.Count(); i++) { **@Html.Span(Model.Assets.ElementAt(i).Id) ** ... and then @Html.DropDownListFor(model => **model.UsersFromTable[i].UserName**, new SelectList(Model.UsersFromTable, "UserName", "UserName")) – matny Apr 10 '18 at 09:58

0 Answers0