2012-03-31 58 views
0

我正在ASP.NET MVC3中使用Razor視圖引擎創建用戶註冊表單。我面臨着爲國家創建下拉列表的問題。國家列表來自xml文件。使用Razor視圖引擎在ASP.NET MVC3中創建下拉列表

我的項目層次結構如下

BusinessLayer - > USER_ACCOUNT - > Account_Registration.cs

這是我想創建一個用戶註冊模型類庫。對於用戶模型的代碼如下

public class Account_Registration 
{ 
    public string User_Name { get; set; } 
    public string User_EmailID { get; set; } 
    public string User_Password { get; set; } 
    public string User_RePassword { get; set; } 
    public DateTime User_BirthDate { get; set; } 
    public enum_Gender User_Gender { get; set; } 
    public string User_Address { get; set; } 
    public string User_City { get; set; } 
    public string User_State { get; set; } 
    public IEnumerable<SelectListItem> User_Country { get; set; } 
    public string User_WebSite { get; set; } 
    public string User_Description { get; set; } 
} 

現在我想知道我應該把國家的XML文件,我怎麼可以創建XML文件的下拉列表。 我的XML文件如下

<countries> 
     <country code="AF" iso="4">Afghanistan</country> 
     <country code="AL" iso="8">Albania</country> 
     <country code="DZ" iso="12">Algeria</country> 
</countries> 

正如我必須部署在IIS上這個項目,所以我想知道我應該把XML文件,這樣就可以在Account_Registration模型,它是在類庫項目和訪問如何爲人口國創建下拉列表。 謝謝

+0

你爲什麼不只是導入XML文件到你的數據庫? – 2012-03-31 16:56:10

+0

僅在表格或內容中導入xml – Awadhendra 2012-03-31 16:57:56

+0

您是否擁有庫?在存儲庫中編寫一個反序列化XML文件並返回一個'List '的方法。更好的是,像@MystereMan建議的那樣,把這些國家放在數據庫中。 – 2012-03-31 16:58:25

回答

1

你可能不應該在每次渲染註冊頁面時閱讀xml文件。由於硬盤操作成本高昂,這可能會是一個小瓶頸。我建議將它讀入內存中(例如應用程序啓動一次,並進入全局變量的某個位置,例如國家/地區)。

爲了呈現您的列表,我建議您查看following文章。基本上,它是這樣的:

Html.DropDownList(「countries」, new SelectList(model.Countries), 「CountryId」, 「CountryName」)) 
+0

這是一個瓶頸,因爲XML反序列化可能很昂貴。如果它在數據庫中,則仍然需要從磁盤讀取它。 :) – 2012-03-31 17:16:32

+0

不是。數據庫可以將經常訪問的數據緩存在內存中,並且它們使用特殊技術更快地從磁盤中獲取數據(更像是在磁盤上查找數據)。反序列化可能會很昂貴,可能不是:) – 2012-03-31 17:18:41

+0

好的,但是,您也可以緩存XML反序列化的結果。這真的取決於OP之後的內容。如果OP想要通過文本文件更改配置,而不是構建基礎架構以將數據庫記錄保存在表單中,那麼XML文件可能是合適的。就個人而言,我只是手動將記錄添加到數據庫表中,並完成它。 – 2012-03-31 17:19:19

0

您可以爲DropDown創建自己的擴展。

public static class GridExtensions 
{ 
    public static MvcHtmlString XmlDropDown(this HtmlHelper helper, string name, string value) 
    { 
     var document = XDocument.Parce(value); 
     var model = new List<SelectListItem>(); 
     foreach(XElement element in document.Elements("countries/country")) 
     { 
      model.Add(new SelectListItem(){Text=element.Value, Value=element.Attribute("iso").Value}) 
     } 

     return Html.DropDownList(name, model)) 
    } 
} 

因此,在視圖中可以使用

Html.XmlDropDown(「countries」, model.Countries) 
相關問題