Loading a list of items from database inside a partial class
Seem's to be a stupid problem but here I go...
I have a table Shops (already added on m开发者_运维技巧y .edmx file) and I have created a partial class Shops in order to add the validation stuff which results in sth like this:
[MetadataType(typeof(ShopsMetaData))]
public partial class Shops
{
}
public class ShopsMetaData
{
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[Display(Name = "Shop name")]
[Required(ErrorMessage = "The field shop name can't be empty")]
public string ShopName { get; set; }
[Required(ErrorMessage = "The field address can't be empty")]
public string Address { get; set; }
[Display(Name = "State")]
[Required(ErrorMessage = "The field state can't be empty")]
public string State { get; set; }
}
The problem is in the "State" property: I could simply leave a textbox and the person can type the state's abbreviation but that wouldn't be so wise. I could put a dropdownlist with the predefined states but I need to get them from the database.
Is there any way I can get the list of states from the database inside this class using a testable code?
What I generally do is that in my Action I set a dynamic property to hold the list of States like this:
ViewBag.States = (from state in context.States
select new SelectListItem {
Text = state.Name,
Value = state.Id.ToString()}
).ToList();
And then my View looks something like this
<div class="editor-label">
@Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.State, (IList<SelectListItem>)ViewBag.States)
</div>
This assumes that your model contains a State
property.
精彩评论