在MVC Nhibernate中创建一个下拉列表 [英] Creating a dropdown list in MVC nhibernate

查看:90
本文介绍了在MVC Nhibernate中创建一个下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在休眠状态下创建一个应用程序,需要在创建视图"中创建一个下拉列表.

I'm creating an application in hibernate where i need to create a dropdown list in my Create View.

通过名为getHobbytype()的函数获取下拉列表项,然后我需要将所选值存储到另一个数据库中.

The dropdownlist items are fetched through a function called getHobbytype() and from that I need to store the selected value into a different database.

我已经在控制器中写了这个:

I have written this in my controller:

ViewData["Hobby_type"] = 
       new SelectList(new  Hobby_MasterService().GetHobbyType(),"Hobby_Types");

这在我的创建视图中:

@Html.DropDownListFor(Model => 
       Model.Hobby_Types,(IEnumerable<SelectListItem>)ViewData["Hobby_type"])

通过此操作,我可以创建下拉列表,但是在我的下拉列表视图中却给了我这个错误:

Through this I'm able to create the dropdown list but it is giving me this error inside my view on the dropdown:

没有类型为"IEnumerable"的ViewData项目具有键"Hobby_Types".

There is no ViewData item of type 'IEnumerable' that has the key 'Hobby_Types'.

这是我的GetHobbyType方法:

Here is my GetHobbyType Method:

 public IList<String> GetHobbyType()
 {
   log.Debug("Started");
   ISession session = DataAccessLayerHelper.OpenReaderSession();
    IList<String> htype = null;
   ITransaction transaction = null;
  try
  {
    transaction = session.BeginTransaction();
    htype = session.CreateSQLQuery("SELECT Hobby_Types FROM Hobby_Type").List<String> ();
  session.Flush();
 transaction.Commit();
}
    catch (Exception ex)
 {
   if (transaction != null && transaction.IsActive)
   transaction.Rollback();
   log.Error(ex);

  }
  log.Debug("End");
  return htype;
  }

请告诉我我要去哪里了.

Please tell me where I'm going wrong.

推荐答案

这是拼写错误:-

@Html.DropDownListFor(Model => 
       Model.Hobby_Types,(IEnumerable<SelectListItem>)ViewData["Type"])

应该不是

@Html.DropDownListFor(Model => 
       Model.Hobby_Types,(IEnumerable<SelectListItem>)ViewData["Hobby_type"])

您的错误也显示'IEnumerable' that has the key 'Hobby_Types'.

ViewData中的键区分大小写(更不用说错误的末尾带有S)

The key in ViewData is case sensitive (not to mention the error has an S on the end)

我也建议使用ViewModel而不是ViewData.参见此

I would also reccomend using a ViewModel rather than ViewData. See this Google search

编辑 GetHobbyType方法返回一个列表,因此请尝试以下操作:-

edit The GetHobbyType Method returns a List so try this:-

 ViewData["Hobby_type"] =    
   new SelectList(
    new Hobby_MasterService().GetHobbyType()
     .Select(x => new SelectListItem { Text = x, Value = x }).ToList()
   ,"Hobby_Types");

我还建议您使用ViewModel,因为它可以为您省去很多麻烦!

I also suggest looking at using a viewmodel as it will save you lots of headaches!

这篇关于在MVC Nhibernate中创建一个下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆