0

In a View i have the next structure ( control of Subject*s for each *Group):

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <div class="form-horizontal">
            @for (int i = 0; i < ViewBag.AllGroups.Count; i++)
            {
                    <h4>@ViewBag.AllGroups[i].Code</h4>

                    <select id="e-@i" multiple="multiple">
                    @foreach (Subject subject in ViewBag.AllSubjects)
                    {
                        <option value="@subject.Name">@subject.Name</option>
                    }
                    </select>
            }
            <input type="submit" value="Generate" class="btn btn-default" />
        </div>
    }

The question is that how can I retreive this data (I want to receive (1)list of Groups and and I want to get a (2)list of all selected Subjects for each group in my list(1)) in my Controller?

Thank you in advance.

3 Answers 3

4

Recommended way is to use strongly typed View Model Object

public class GroupViewModel
{
 public string Code { get;set; }
 public List<Subject> AllSubjects { get; set; }
}

Pass List as the Model to the Razor view in the controller.

return new View(new List<GroupViewModel>());  // populated one.

Use this list in the View.

@model IList<GroupViewModel>

@for (int i = 0; i < Model.Count; i++)
{
 <h4>Model[i].Code</h4>

 <select id="e-@i" multiple="multiple">
 @foreach (Subject subject in Model[i].AllSubjects)
 {
  <option value="@subject.Name">@subject.Name</option>
 }
 </select>
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. GroupViewModel is useful in my situation, however the problem isn't in the passing of the data data from Controller to View but in retrieving all selected subjects in my <select> controls for all of my groups in my Controller after the button "Generate" is clicked.
can you explain more? are you looking for the DropdownListFor helper?
Already solved my question: the answer is below. Thank you for helping me.
0

There is nothing especial to deal with this situation, except that you have missed the tag name of the select element.

To be exact, all html elements such as select you have used here, should have a name not id (id="e-@i") and all elements are serialized based their names and sent to server. On the other side, at server-side, you should get the posted values which are in a csv formatted (due to multiple ability added you have added to select element)

Comments

0

Solved my problem by simplifying the task. What i had to to: I created new ViewModel for this thing. I replaced tag
<select></select> with
@Html.ListBoxFor(m => m.Subjects, Model.SubjectItems). I had to create a SubjectItems list in my ViewModel.
Here's the code (Sorry for tons of code: I just want to make everything clear):
My View:

@using System
@using System.Linq
@using TimeTable.GenericRepository
@model TimeTable.Models.GroupViewModel

@{
    //it's better to move the next line to a Controller later
    ViewBag.GroupId = new SelectList(new GroupRepository().Get().ToList(), "Id", "Code", Model.GroupId);

    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutBootstrap.cshtml";
}

<h2>Index</h2>
<hr />

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.GroupId, "Group is: ", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("GroupId", String.Empty)
                @Html.ValidationMessageFor(model => model.GroupId)
            </div>
        </div>

        @Html.ListBoxFor(m => m.Subjects, Model.SubjectItems, new { @id = "e", @style = "width:80%; " })
        <br /><br />
        <input type="submit" value="Generate" class="btn btn-default" />
    </div>
}

@* ReSharper disable once Razor.SectionNotResolved *@
@section Scripts {
    @Styles.Render("~/Content/select2")
    @Scripts.Render("~/bundles/select2")

    <script type="text/javascript">
        $(function () { $("#e").select2(); });
    </script>
}

My Controller:

public ActionResult Generate()
{

    return View(new GroupViewModel());
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Generate(GroupViewModel gvm)
{
    var subjects= gvm.Subjects; // <== selected subjects are here
    return View();
}

My Model:

public class GroupViewModel
{
    public int GroupId{ get; set; }

    public Group Group {
        get { return new GroupRepository().GetById(GroupId); }
    }

    public object Subjects { get; set; }

    public IEnumerable<SelectListItem> SubjectItems
    {
        get
        {
            var items = new SelectList(new SubjectRepository().Get().ToList(), "Id", "Name");
            return items; 
        }
    }
}

P.S. Select2 is a custom replacement for selectBoxes, it's not necessary, but I like it: http://ivaynberg.github.io/select2/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.