问题
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?
回答1:
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])
}
回答2:
Try placing the "EventRange.cshtml" in the “~/Views/Shared/EditorTemplates/” folder.
来源:https://stackoverflow.com/questions/13420791/mvc-editorfor-not-working-for-collection