मैं वर्तमान में इस तरह से खुश नहीं हूं कि मेरी DropDownListFor() ऑब्जेक्ट्स आबादी वाले हैं। मैं यथासंभव IENumerable populating के सामान्य तरीके के रूप में खोजने का प्रयास कर रहा हूँ। अभी तक मेरे पास इतना ही है।एएसपी.नेट एमवीसी 3 सूची <T> आईनेमेरेबल <selectListItem>
हेल्पर:
public static List<SelectListItem> ToSelectList(IDictionary<string,string> dictionaryItems, string selectedValue, string noSelection, bool search = false)
{
List<SelectListItem> items = new List<SelectListItem>();
if (search)
{
items.Add(new SelectListItem { Selected = true, Value = "-1", Text = string.Format("-- {0} --", noSelection) });
}
foreach (var item in dictionaryItems)
{
items.Add(new SelectListItem
{
Text = item.Key,
Value = item.Value,
Selected = selectedValue == item.Value ? true : false
});
}
return items
.OrderBy(l => l.Text)
.ToList();
}
नियंत्रक:
[HttpGet]
public ActionResult Index()
{
var model = new CreateModel();
var parentOrganisations = _orgs.FindBy(o => o.OwningOrganisationID == Globals.OrganisationID || o.ID == Globals.OrganisationID)
.OrderBy(o => o.OrganisationName);
Dictionary<string, string> items = new Dictionary<string, string>();
foreach (var item in parentOrganisations)
{
items.Add(item.OrganisationName, item.ID.ToString());
}
model.Organisations = SelectLists.ToSelectList(items, "-1", "-- None -- ", true);
return View(model);
}
दृश्य:
<div class="control-group">
<label class="control-label">Parent Organisation</label>
<div class="controls">
@Html.DropDownListFor(m => m.ParentOrganisationID, Model.Organisations, new { @class = "input-xlarge"})
<p class="help-block">Select a parent organisation to create a branch</p>
</div>
</div>
वहाँ नियंत्रक में दोहराव कोड का एक बहुत हो रहा है। यह एक सामान्य सूची लेता है, एक शब्दकोश में मूल्य और पाठ जोड़ता है और उसके बाद उस सहायक के लिए इनपुट के रूप में उपयोग करता है जो मॉडल के हिस्से के रूप में भेजने के लिए चयन सूची बनाता है।
क्या किसी को यह हासिल करने के लिए कोई बेहतर तरीका है? मुझे अपने नियंत्रक में ब्लोट होने से नफरत है, और जब मुझे एक फॉर्म पर कई ड्रॉप डाउन मिलते हैं तो यह वास्तव में इस घटना में क्या होगा।
धन्यवाद,
संपादित करें - केनेथ सहायक विधि के लिए धन्यवाद, मैं अब समेकित किया है नियंत्रक में एक कॉल में पूरी बात:
model.Organisations = _orgs.FindBy(o => o.OwningOrganisationID == Globals.OrganisationID || o.ID == Globals.OrganisationID)
.OrderBy(o => o.OrganisationName)
.ToList()
.ToSelectList(org => org.OrganisationName, org => org.ID.ToString(), "-1", "None", true);
धन्यवाद! यह वही है जो मैं उम्मीद कर रहा था। – Paul