我有一個冗長的表格,我已經打破了幾個部分,並使用@ Html.EditorFor爲每個部分工作很好,但需要你的想法是否可以改進這種方法或不。將一個集合傳遞給EditorFor ASP.NET在ASP.NET MVC
有細分市場,每個細分市場都可以有多個活動,所以我有一個細分市場集合,此集合中的每個細分市場都包含一系列活動。
public class Activity
{
public string ActivityId { get; set; }
public string ActivityDescription { get; set; }
public bool IsSelected { get; set; }
}
public class Segment
{
public string SegmentId { get; set; }
public string SegmentDescription { get; set; }
public List<Activity> Activitites { get; set; }
}
這是我怎麼想,我作爲視圖應該看起來像一個模型中使用,但不能做,因爲@ Html.EditorFor它的工作沒有接受集合類型的視圖模型。
public class UserPreferencesViewModel
{
//..... Other Properties
public List<Segment> Segments {get; set;}
}
這裏是視圖模型
@model UserPreferencesViewModel
@{
//... Other Properties
@Html.EditorFor(m => m.Segments) //I assigned Segments three Segments in the Controller Get Method
}
這裏是EditorFor模板段
@model List<Segment>
@{
//... Other Properties
@foreach(var segment in Model)
{
//Do the stuff
}
}
但這不起作用說EditorFor不能以集合和異常在運行時拋出。
這是我的工作。我創建了另一個類「UglySegmentWorkAround」,其中包含段集合,然後在UserPreferencesViewModel中刪除了列表屬性,而是爲此定義了一個屬性。
public class UglySegmentWorkAround
{
public List<Segment> Segments {get; set;}
}
public class UserPreferencesViewModel
{
//..... Other Properties
public UglySegmentWorkAround UglySegmentWorkAround {get; set;}
}
這裏是EditorFor Template。
@model UglySegmentWorkAround
@{
//... Other Properties
@foreach(var segments in Model.Segments)
{
//Do the stuff
}
}
它完美的作品,但我只是感覺不舒服這種做法,是有什麼我在第一種方法缺少什麼?這應該如何完成?如果我將它傳遞給一個集合,我不想讓EditorFor做一個隱式循環,因爲我正在EditorFor中渲染一個複雜的UI結構,並且我需要EditorFor將其中的循環。
檢查此鏈接(http://stackoverflow.com/questions/13420791/mvc-editorfor-not-working-for-collection) – 2014-09-26 21:41:07
@HasanFahim我不喜歡我不想在EditorFor外寫一個for循環,就像我在我的問題中提到的那樣,而是我的UI需要我循環編輯器中的集合。 – 2014-09-26 22:47:58