SelectList
निर्माता (जिसमें आपके द्वारा चयनित मूल्य आईडी पारित करने के लिए सक्षम होने की आशा) की अंतिम तर्क को नजरअंदाज कर दिया क्योंकि DropDownListFor सहायक लैम्ब्डा अभिव्यक्ति आप पहले तर्क के रूप में पारित उपयोग करता है और विशिष्ट संपत्ति के मूल्य का उपयोग करता है।
तो यहाँ करने के लिए बदसूरत तरीका है कि:
मॉडल:
public class MyModel
{
public int StatusID { get; set; }
}
नियंत्रक:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
ViewBag.Statuses = statuses;
var model = new MyModel();
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}
दृश्य:
@model MyModel
...
@Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)
और यहाँ सही तरीका नहीं है, वास्तविक दृश्य मॉडल का उपयोग:
मॉडल
public class MyModel
{
public int StatusID { get; set; }
public IEnumerable<SelectListItem> Statuses { get; set; }
}
नियंत्रक:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
var model = new MyModel();
model.Statuses = statuses;
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}
दृश्य:
@model MyModel
...
@Html.DropDownListFor(model => model.StatusID, Model.Statuses)
नीचे दिए गए लिंक देखें। http://stackoverflow.com/questions/5188563/asp-net-mvc-drop-down-list-selection-partial-views-and-model-binding –
alok_dida, मैं उस पर देखा, यह बहुत लग रहा है सिवाय इसके कि सिलेक्टलिस्ट का चयन करने में चयनित मान पूरे ऑब्जेक्ट बनाम ID.ToString() जैसा मैं कर रहा हूं। हालांकि मैंने अपना कोड वही करने के लिए बदल दिया और इसने समस्या को हल नहीं किया। क्या उन दोनों के बीच कुछ अंतर है जो मुझे याद आ रही हैं जो मेरी समस्या को ठीक करेगी? – azorr
मैंने एक विस्तृत उदाहरण जोड़ा कि यह कैसे किया जा सकता है। इस –