MVC editorfor not working for collection
Asked Answered
W

2

1

I have a model class called Events and a model class called EventRange:

public class Event
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public List<EventRange> RangesCollection { get; set; }
}

public class EventRange
{
    public int Id { get; set; }

    public string RangeName { get; set; }
    public string RangeDescription { get; set; }
    public int Capacitiy { get; set; }
}

As you can see the Event class contains a List for as many EventRanges as the user should be able to add a lot of EventRanges.

I have created a view called events, which dynamicly appends a partial view for the evenrange. The user can in example press the Add Event Range button 5 times if he want's 5 EventRanges saved.

The Event view:

@using (Ajax.BeginForm("CreateEvent", "Events", new AjaxOptions { HttpMethod = "POST" }, new { @class = "mainForm" }))
{
    @*Event data:*@
    @Html.LabelFor(m => m.Name)@Html.TextBoxFor(m => m.Name)
    @Html.LabelFor(m => m.Description)@Html.TextBoxFor(m => m.Description)

    @*EventRange data:*@

    <div id="EventRangediv">
    @Html.EditorFor(m => m.RangesCollection)
    </div>

}

The partial view for the eventrange is saved under "~/views/events/EditorTemplates/EventRange.cshtml"

EventRange.cshtml:

@model fanaticksMain.Models.EventRange

@Html.HiddenFor(m => m.Id)
@Html.DisplayFor(m => m.RangeName)
@Html.LabelFor(m => m.RangeName)@Html.TextBoxFor(m => m.RangeName)
@Html.LabelFor(m => m.RangeDescription)@Html.TextBoxFor(m => m.RangeDescription)

However, loading the events view doesn't load any element from the partialview, the labels and textboxes for the name and description for the event work. But nothing is shown for the eventrange partial view.

Anyone have anyone idea what I'm doing wrong? Also, does anyone have any suggestion if this is the right way to bind a collection for posting a form?

Weekend answered 16/11, 2012 at 16:42 Comment(0)
O
2

EventRange.cshtml has the model specified as EventRange. m.RangesCollection is a collection of EventRange objects.

I don't see a model that is defined as accepting a collection of EventRange.

try place a for loop in your code to iterate each EventRange and display the EventRange.cshtml editor for each one:

Instead of:

@Html.EditorFor(m => m.RangesCollection)

Try:

@for (int i = 0; i < m.RangeCollection.Count; i++)
{
    @Html.EditorFor(m => m.RangeCollection[i])
}
Olney answered 16/11, 2012 at 18:45 Comment(2)
The collection doesn't contain any items, the view is for adding items to the rangecollection.Weekend
You may want to take a look at this article: Editing a variable-length list of itemsOlney
S
0

Try placing the "EventRange.cshtml" in the “~/Views/Shared/EditorTemplates/” folder.

Seljuk answered 16/11, 2012 at 16:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.