Creating a dropdown list in MVC nhibernate

2019-08-20 20:47发布

问题:

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

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");

And this in my Create View:

@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:

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

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.

回答1:

Is this a typo:-

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

Should it not be

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

Also your error says 'IEnumerable' that has the key 'Hobby_Types'.

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

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

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");

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



回答2:

You can try this all.

You have to write a service named GetAllStudents()

public IList<Student> GetAllStudents()
{

    log.Debug("Started");
    ISession session = DataAccessLayerHelper.OpenReaderSession();
    IList<Student> students = null;
    ITransaction transaction = null;
    try
    {
        transaction = session.BeginTransaction();

        ICriteria criteria = session.CreateCriteria(typeof(Student));
        students = criteria.List<Student>();
        session.Flush();
        transaction.Commit();
    }
    catch (Exception ex)
    {
        if (transaction != null && transaction.IsActive)
            transaction.Rollback();
        log.Error(ex);

    }
    finally
    {
        if (transaction != null)
            transaction.Dispose();

        if (session != null && session.IsConnected)
            session.Close();
    }

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

In controller:

ViewBag.std = new StudentService().GetAllStudents(); // ViewBag.std will hold all students.

In create View:

@Html.DropDownListFor(model => model.Name, new SelectList(ViewBag.std, "Id", "Name"), "-- Select --")
  • First parameter is responsible for Linq expression for class property which you want to place in dropdown.
  • Second one is IEnumerable item list.
  • Third data value field.(Primary key)
  • Last one is Data text field which you want to display in drop down list.