Vid*_*dya 0 asp.net select asp.net-mvc-3
我需要使用nHibernate映射填充数据库字段中的数据,用于ASP.net MVC3中的select ...请给我一个如何做的示例代码..
关心Srividhya
您可以从定义视图模型开始:
public class MyViewModel
{
    public string SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}
然后是一个控制器,它将填充这个视图模型(在开始时硬编码一些值,以确保它工作,你有一个模型屏幕显示给你的用户):
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Items = new[] 
            {
                new SelectListItem { Value = "1", Text = "item 1" },
                new SelectListItem { Value = "2", Text = "item 2" },
                new SelectListItem { Value = "3", Text = "item 3" },
            }
        };
        return View(model);
    }
}
最后一个观点:
@model MyViewModel
@Html.DropDownListFor(
    x => x.SelectedItemId, 
    new SelectList(Model.Items, "Value", "Text")
)
下一步可能包括定义模型,设置此模型的映射,存储库允许您使用NHibernate获取模型,最后在控制器操作中调用此存储库并将返回的模型映射到我在示例中使用的视图模型:
模型:
public class Item
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}
库:
public interface IItemsRepository
{
    IEnumerable<Item> GetItems();
}
现在控制器变成:
public class HomeController : Controller
{
    private readonly IItemsRepository _repository;
    public HomeController(IItemsRepository repository)
    {
        _repository = repository;
    }
    public ActionResult Index()
    {
        var items = _repository.GetItems();
        var model = new MyViewModel
        {
            Items = items.Select(item => new SelectListItem
            {
                Value = item.Id.ToString(),
                Text = item.Name
            })
        };
        return View(model);
    }
}
好的,我们正在逐步取得进展.现在,您可以为此控制器操作编写单元测试.
下一步是实现此存储库:
public class ItemsRepositoryNHibernate : IItemsRepository
{
    public IEnumerable<Item> GetItems()
    {
        throw new NotImplementedException(
            "Out of the scope for this question. Checkout the NHibernate manual"
        );
    }
}
最后一步是指示您的依赖注入框架将存储库的正确实现传递给HomeController.例如,如果你使用Ninject,你需要做的就是编写一个配置内核的模块:
public class RepositoriesModule : StandardModule 
{
    public override void Load() 
    {
        Bind<IItemsRepository>().To<ItemsRepositoryNHibernate>();
    }
}
| 归档时间: | 
 | 
| 查看次数: | 1270 次 | 
| 最近记录: |