Reputation: 513
I am creating a User Registration form in ASP.NET MVC3 using razor view engine. I am facing problem to create a dropdownlist for country. Country list come from xml file.
My project hierarchy is as follows
BusinessLayer -> User_Account -> Account_Registration.cs
This is a class library in which I want to create a Model for user registration. The code for user model is as follows
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; }
}
Now I want to know that where I should put country XML file and how can I create dropdownlist for XML file. My Xml file is as follows
<countries>
<country code="AF" iso="4">Afghanistan</country>
<country code="AL" iso="8">Albania</country>
<country code="DZ" iso="12">Algeria</country>
</countries>
As I have to deploy this project on IIS so I want to know where should I put xml file so that I can access it in Account_Registration model which is in class library project and how to create dropdownlist for population countries. Thanks
Upvotes: 0
Views: 3653
Reputation: 61
you can create own extension for 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))
}
}
So, on view you can use
Html.XmlDropDown(“countries”, model.Countries)
Upvotes: 0
Reputation: 6862
You probably shouldn't read xml file each time you render registration page. That would be one little bottleneck you'd have since hard drive operations are costly. I'd recommend reading it into memory (like at the application startup once and somewhere into the global variable, e.g. Countries).
For rendering your list, I'd recommend looking at the following article. Basically, it goes like this:
Html.DropDownList(“countries”, new SelectList(model.Countries), “CountryId”, “CountryName”))
Upvotes: 1