in this article, I will show you how to use tuple in asp.net mvc
example :
public class EmployeeModel
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
}
public JsonResult GetEmployeeData(int? id)
{
try
{
var data = GetEmployee_List(id);
var dt = data.Item2;
var list = new List<EmployeeModel>();
for (var i = 0; i < dt.Rows.Count; i++)
{
var obj = new EmployeeModel()
{
Id = Convert.ToInt16(dt.Rows[i]["Id"]),
Name = Convert.ToString(dt.Rows[i]["Name"]),
Salary = Convert.ToDecimal(dt.Rows[i]["Salary"]),
};
list.Add(obj);
}
var result = list.Select(x => new EmployeeModel()
{
Id = x.Id,
Name = x.Name,
Salary = x.Salary,
}).ToList();
var totalRecords = data.Item1;
return Json(new
{
recordsTotal = totalRecords,
data = result.ToList()
});
}
catch (Exception)
{
throw;
}
}
public static SqlConnection StaticSqlConnection
{
get
{
SqlConnection staticConnection = new SqlConnection();
staticConnection.ConnectionString = "Data Source =.; Integrated Security = true; Initial Catalog = TESTDB";
return staticConnection;
}
}
public static Tuple<int, DataTable> GetEmployee_List(int? id)
{
var staticConnection = StaticSqlConnection;
var command = new SqlCommand
{
CommandText = "get_emp_rec",
CommandType = CommandType.StoredProcedure,
Connection = staticConnection
};
command.Parameters.AddWithValue("@id", id);
var parTotalCount = new SqlParameter("@recordcount", SqlDbType.Int) { Direction = ParameterDirection.Output };
command.Parameters.Add(parTotalCount);
var objDataAdapter = new SqlDataAdapter();
var ds = new DataSet();
try
{
staticConnection.Open();
objDataAdapter.SelectCommand = command;
objDataAdapter.Fill(ds);
var objUserReturnValue = Tuple.Create((int)parTotalCount.Value, ds.Tables[0]);
staticConnection.Close();
return objUserReturnValue;
}
catch
{
throw;
}
finally
{
ds.Dispose();
objDataAdapter.Dispose();
staticConnection.Close();
command.Dispose();
}
}
0 Comments
if you have any doubts , please let me know