2013-02-16 2 views
2

Я работаю с mvc4 бритвой, это первый код моделиASP.Net MVC множественный список возвращения из контроллера

public class WebLicenses 
{ 
    public string WebLicenseName { get; set; } 
    public int CustomerWebLicensesCount { get; set; } 
} 

public class WebApplication 
{ 
    public string WebApplicationName { get; set; } 
    public int Count { get; set; } 

    [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")] 
    public DateTime? EndDate { get; set; } 

    public string Never { get; set; } 
} 
public class griddetail 
{ 
    public griddetail(List<WebLicenses> wl1,List<WebApplication> wa1) 
    { 
     wl =wl1; 
     wa = wa1; 
    } 
    //public List<WebLicenses> wl2 { get; private set; } 

    public List<WebLicenses> wl { get; set; } 
    public List<WebApplication> wa { get; set; } 

} 

это мой второй код модели, которые используют первый код модели как (здесь хранится возвращение процедура 2 таблицы - WebLicenses, WebApplication (В ниже код ошибки приходит --commented)

 public IEnumerable GetOutlookGridDetail(string customerId = "") 
    { 
     List<WebLicenses> weblicenses = new List<WebLicenses>(); 
     List<WebApplication> webapplication = new List<WebApplication>();    
     griddetail returnValue = new griddetail(weblicenses, webapplication);   

     SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SLIMConnectionString"].ConnectionString); 
     SqlCommand cmd = new SqlCommand("selectCustomerDetail", cn); 
     cmd.CommandType = CommandType.StoredProcedure; 

     SqlParameter param_CustomerID = new SqlParameter("@CustomerID", SqlDbType.VarChar, 10); 
     param_CustomerID.Value = customerId; 
     cmd.Parameters.Add(param_CustomerID); 

     try 
     { 
      cn.Open(); 

      SqlDataReader reader = cmd.ExecuteReader(); 

      while (reader.Read()) 
      { 
       WebLicenses newRecord = new WebLicenses(); 
       newRecord.WebLicenseName = Convert.ToString(reader["WebLicenseName"]); 
       newRecord.CustomerWebLicensesCount = Convert.ToInt32(reader["CustomerWebLicensesCount"]); 
       //returnValue.Add(newRecord); 
       weblicenses.Add(newRecord);      
      } 

      reader.NextResult(); 

      while (reader.Read()) 
      { 
       WebApplication newRecord = new WebApplication(); 

       newRecord.WebApplicationName = Convert.ToString(reader["WebApplicationName"]); 
       newRecord.Count = Convert.ToInt32(reader["Count"]); 
       newRecord.Never = Convert.ToString(reader["Never"]); 
       webapplication.Add(newRecord); 
      } 
      returnValue.wl.Add(weblicenses); //here comes error (Argument 1: cannot convert from 'System.Collections.Generic.List<SLIM.Models.WebLicenses>' to 'SLIM.Models.WebLicenses') 
     } 
     catch (Exception) 
     { 
      // returnValue = null; 
     } 
     finally 
     { 
      cmd.Dispose(); 

      if (cn.State == ConnectionState.Open) 
      { 
       cn.Close(); 
      } 
     } 

     return returnValue; 
    } 

это мой код контроллера

[HttpPost] 
    public ActionResult GridViewPartialView(string recordId) 
    { 
     IEnumerable result1 = (new SlimHomePageData()).GetRecords(recordId, ""); 
     IEnumerable result2 = (new SlimHomePageData()).GetRecords(); 
     List<object> finalResult = new List<object>(); 
     finalResult.Add(result1); 
     finalResult.Add(result2); 
     return PartialView("OutlookGridDetail", finalResult);    
    } 
.

Я хочу вернуть единственный список, состоящий из 2-х списков (но выше ошибки). Также предположим, что это правильный подход, поскольку хранимая процедура возвращает несколько таблиц, и мы хотим установить значение в поле зрения через модель.

ответ

3

Я забыл дать ответ, но вчера кто-то дает минус голосование. Да, слишком долго. То, что я сделал (я снова объяснить все, чтобы понять больше):

Шаг1: Определение 2-го класса, как

public class WebLicenses 
    { 
     public int WebLicenseID { get; set; } 
     public string WebLicenseName { get; set; } 
     public int CustomerWebLicensesCount { get; set; } 
     public string CreatedBy { get; set; } 
     public string UpdatedBy { get; set; } 
    } 

public class WebApplication 
{ 
    public int appID { get; set; } 
    public string WebApplicationName { get; set; } 
    public int Count { get; set; } 

    [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")] 
    public DateTime? EndDate { get; set; } 

    public bool Never { get; set; } 
    public string CreatedBy { get; set; } 
    public string UpdatedBy { get; set; } 
} 

public class griddetail 
{ 
    public griddetail(List<WebLicenses> wl1, List<WebApplication> wa1) 
    { 
     weblicences = wl1; 
     webapplication = wa1; 
    } 

    public List<WebLicenses> weblicences { get; set; } 
    public List<WebApplication> webapplication { get; set; }   
} 

Step2: изменения в контроллере, как

  1. Изменить тип возвращаемого значения IEnumerable до griddetail класс
  2. В конце объявить и назначить эту вложенную группу s в griddetail классе

    public class SlimHomePageData 
    { 
        private SLIMDataContext dc = new SLIMDataContext(ConfigurationManager.ConnectionStrings["SLIMConnectionString"].ConnectionString); 
    . 
    . 
    . 
    
    public IEnumerable GetOutlookGridDetail(string customerId = "") 
    { 
        List<WebLicenses> weblicenses = new List<WebLicenses>(); 
        List<WebApplication> webapplication = new List<WebApplication>();    
        //remove from here and add at the end of this method 
        //griddetail returnValue = new griddetail(weblicenses, webapplication);   
    
        SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SLIMConnectionString"].ConnectionString); 
        SqlCommand cmd = new SqlCommand("selectCustomerDetail", cn); 
        cmd.CommandType = CommandType.StoredProcedure; 
    
        SqlParameter param_CustomerID = new SqlParameter("@CustomerID", SqlDbType.VarChar, 10); 
        param_CustomerID.Value = customerId; 
        cmd.Parameters.Add(param_CustomerID); 
    
        try 
        { 
        cn.Open(); 
    
        SqlDataReader reader = cmd.ExecuteReader(); 
    
         if (reader.HasRows) 
         { 
          while (reader.Read()) 
          { 
           WebLicenses newRecord = new WebLicenses(); 
           newRecord.WebLicenseName = Convert.ToString(reader["WebLicenseName"]); 
           newRecord.CustomerWebLicensesCount = Convert.ToInt32(reader["CustomerWebLicensesCount"]); 
           weblicenses.Add(newRecord); 
          } 
         } 
    
         reader.NextResult(); 
         if (reader.HasRows) 
         { 
          while (reader.Read()) 
          { 
           WebApplication newRecord = new WebApplication(); 
    
           newRecord.WebApplicationName = Convert.ToString(reader["WebApplicationName"]); 
           newRecord.Count = Convert.ToInt32(reader["Count"]); 
    
           bool never = false; 
    
           if (reader["Never"] != DBNull.Value) 
           { 
            bool.TryParse(reader["Never"].ToString(), out never); 
           } 
    
           if (reader["EndDate"] != DBNull.Value) 
           { 
            newRecord.EndDate = Convert.ToDateTime(reader["EndDate"]); 
           } 
    
           newRecord.Never = never; 
    
           webapplication.Add(newRecord); 
          } 
         } 
    
    
        reader.Close(); 
    
        } 
        catch (Exception) 
        { 
         // returnValue = null; 
        } 
        finally 
        { 
         cmd.Dispose(); 
    
         if (cn.State == ConnectionState.Open) 
         { 
          cn.Close(); 
         } 
        } 
    
         griddetail returnValue = new griddetail(weblicenses, webapplication, webcustomapplication, maintenance, smartcv, histry, doc); 
        return returnValue; 
        } 
        . 
        . 
        }//closing of my SlimHomePageData class 
    

** Шаг 3: ** В ActionMethod изменилось: После отвечал на этот вопрос, я изменил в методе, но вы можете использовать ту же концепцию метода в поставленный выше вопрос. Позже мне нужен еще один класс, чтобы добавить result1 во время возвращения.

 public ActionResult GridViewPartialView() 
{ 
      return View(); 
} 


[HttpPost] 
     public ActionResult childGridViewPartialView(string recordId, string filtervalue, string flag) 
     { 
      if (flag == "GridRowChanged") 
      { 
       IEnumerable result1; 
       griddetail result3; 
       if (recordId != null) 
       { 
        result1 = (new SlimHomePageData()).GetRecords(recordId, ""); //another result to be add later at the end of action method 
        result3 = (new SlimHomePageData()).GetOutlookGridDetail(recordId); //this was in my question 
       } 
       else 
       { 
        result1 = new List<SlimHomePageRecord>(); //another result to be add later at the end of action method 
        result3 = (new SlimHomePageData()).GetOutlookGridDetail(recordId); //this was in my question 
       } 

       List<object> finalResult = new List<object>(); 
       finalResult.Add(result1); 
       finalResult.Add(result3); 
       return PartialView("OutlookGridDetail", finalResult); 
      } 
      else 
      { 
       return PartialView("childGridViewPartialView", (new SlimHomePageData()).GetRecords(null, null)); 
      } 
     } 
0

экземпляр weblicenses - это тип списка. Похоже, что это должен быть единственный экземпляр WebLicenses.

Возможно, вы захотите добавить экземпляр newRecord в список returnValue.wl вместо экземпляра списка.

Редактировать: Вам не нужно ничего добавлять к свойствам списка wl, потому что вы добавляете в список WebLicenses. Свойство wl on returnValue является ссылкой на экземпляр WebLicences, поэтому, если вы добавите в WebLicences, тогда wl покажет одно и то же дополнение.