PDA

View Full Version : how bind xml to Html.DrowpDownList?



javad_r_85
دوشنبه 23 خرداد 1390, 10:34 صبح
سلام

چطور می شه یک dropdown list را به فایل xml متصل کرد . در این فایل اسامی استانها و شهرها قرار دارد و الان می خوام توی صفحه اونا را نمایش بدم چطور می تونم این کار را بکنم؟؟؟؟

javad_r_85
شنبه 28 خرداد 1390, 22:17 عصر
سلام بالاخر ه بعد از چن روز کلنجاررفتن باش و پرسیدن سوال در msdn و stackoverflow به جواب رسیدم که طبق زیر است


<?xml version="1.0" encoding="utf-8"?>
<CRM>
<Unit ID="1" Name="آذربایجان شرقی">
<city ID="1">آذرشهر </city>
<city ID="2">اسکو </city>
<city ID="3">اهر </city>
<city ID="12">کلیبر </city>
<city ID="13">مراغه </city>
<city ID="14">مرند </city>
<city ID="15">ملکان </city>
<city ID="16">ملکان </city>
<city ID="17">میانه </city>
<city ID="18">ورزقان </city>
<city ID="19">هریس </city>
<city ID="20">هشترود</city>
</Unit>

<Unit ID="2" Name="آذربایجان غربی">
<city ID="1">ارومیه </city>
<city ID="2">اشنویه </city>
<city ID="3">بوکان </city>
<city ID="4">پیرانشهر </city>
<city ID="5">تکاب </city>
<city ID="6">چالدران </city>
</Unit>

<Unit ID="3" Name="اردبیل">
<city ID="1">اردبیل </city>
<city ID="2">بیله‌سوار </city>
</Unit>

<Unit ID="4" Name="اصفهان">
<city ID="1">آران و بیدگل</city>
<city ID="2">اردستان </city>
<city ID="3">اصفهان </city>
<city ID="4">برخوار و میمه</city>
<city ID="5">تیران و کرون</city>
<city ID="6">چادگان </city>
<city ID="7">خمینی‌شهر </city>
<city ID="8">خوانسار </city>
<city ID="9">سمیرم </city>
<city ID="10">شهرضا"</city>
<city ID="11">سمیرم سفلی"</city>
<city ID="12">فریدن"</city>
</Unit>
</CRM>




در قسمت مدل یک کلاس اضافه می کنیم مانند زیر




public class UnitViewModel
{
public string SelectedID { get; set; }
public IEnumerable<SelectListItem> Units { get; set; }
}



و اما




public ActionResult Index()
{
// TODO: it would be better to externalize the parsing of the XML
// file into a separate repository class to avoid cluttering your
// controller actions with such code which is not what they should
// be responsible for. But for the purpose of this answer it should
// be enough

var file = Path.Combine(Server.MapPath("~/app_data"), "crm.xml");
var model = new UnitViewModel
{
Units =
from unit in XDocument.Load(file).Document.Descendants("Unit")
select new SelectListItem
{
Value = unit.Attribute("ID").Value,
Text = unit.Attribute("Name").Value
}
};
return View(model);
}





و در قسمت ویو



<%= Html.DropDownListFor(
x => x.SelectedID,
new SelectList(Model.Units, "Value", "Text")
) %>