Pass object to another action of ASP.net MVC 2 - asp.net-mvc

I have one view that used to display the result of my search item. This is its controller :
[HttpPost]
public ActionResult EvaluatingReport(FormCollection frm)
{
string empType = frm["empType"].ToString();
int totalMonth = 3;
int mon = DateTime.Now.Month;
int yr = DateTime.Now.Year;
string Curdate = mon + "/" + yr;
DateTime date = new DateTime();
var result = (from e in context.tblEmployees
join p in context.tblEmployee_Position on e.PositionIDF equals p.PositionID
select new EvaluateEmployee
{
ID = e.Code,
IDCard = e.IDCard,
Name = e.NameEng,
DOB = e.DOB,
Position = p.Position,
Sex = e.Sex,
StartDate = e.StartDate
}).ToList();
result = result.Where(((s => mon - int.Parse(s.StartDate.Substring(3, 2).ToString()) == totalMonth && yr -int.Parse(s.StartDate.Substring(6, 4).ToString()) == totalYear))).ToList();
ViewData["EmployeeType"] = result;
return View();
}
I displayed the content in the view by looping ViewData["EmployeeType"] and I also included one Print label :
<script language="javascript" type="text/javascript">
function printChart() {
var URL = "EvaluatingReport";
var W = window.open(URL);
W.window.print();
}
function printPage(sURL) {
var oHiddFrame = document.createElement("iframe");
oHiddFrame.src = sURL;
oHiddFrame.style.visibility = "hidden";
oHiddFrame.style.position = "fixed";
oHiddFrame.style.right = "0";
oHiddFrame.style.bottom = "0";
document.body.appendChild(oHiddFrame);
oHiddFrame.contentWindow.onload = oHiddFrame.contentWindow.print;
oHiddFrame.contentWindow.onafterprint = function () {
document.body.removeChild(oHiddFrame); };
}
</script>
<span onclick="printPage('/Report/PrintEvaluatingReport');" style="cursor:pointer;text-decoration:none;color:#0000ff;">
<img src="../../Content/images/Print.png" width="35px;" alt="print" style="position:relative;top:6px;"/>
Print Report
</span>
I used function printPage('/Report/PrintEvaluatingReport') to load the print dialog with the action PrintEvaluatingReport. So I want to take the object that I have in EvaluatingReport to the action PrintEvaluatingReport.
Could anyone tell me how could I do that?
Thanks in advanced.

You could use TempData["EmployeeType"]
[HttpPost]
public ActionResult EvaluatingReport(FormCollection frm)
{
string empType = frm["empType"].ToString();
int totalMonth = 3;
int mon = DateTime.Now.Month;
int yr = DateTime.Now.Year;
string Curdate = mon + "/" + yr;
DateTime date = new DateTime();
var result = (from e in context.tblEmployees
join p in context.tblEmployee_Position on e.PositionIDF equals p.PositionID
select new EvaluateEmployee
{
ID = e.Code,
IDCard = e.IDCard,
Name = e.NameEng,
DOB = e.DOB,
Position = p.Position,
Sex = e.Sex,
StartDate = e.StartDate
}).ToList();
result = result.Where(((s => mon - int.Parse(s.StartDate.Substring(3, 2).ToString()) == totalMonth && yr -int.Parse(s.StartDate.Substring(6, 4).ToString()) == totalYear))).ToList();
ViewData["EmployeeType"] = result;
// Store in TempData to be read by PrintEvaluatingReport
TempData["EmployeeType"] = result;
return View();
}
public ActionResult PrintEvaluatingReport()
{
var employeeType = TempData["EmployeeType"] as EmployeeType;
// do stuff
return View();
}

You can use a session variable for that !!
private EmployeeType Result
{
get { return (EmployeeType)this.Session["Result"]; }
set
{
this.Session["Result"] = value;
}
}
[HttpPost]
public ActionResult EvaluatingReport(FormCollection frm)
{
.
.
.
// Store in Session
this.Result = result;
return View();
}
public ActionResult PrintEvaluatingReport()
{
var employeeType = this.Result;
.
.
.
}

Related

linq to entity does not recognize the method

I need to call a method FormatCourseTitle() from linq query but receive error message "Linq to Entity does not recognize the method FormatCourseTitle..." How to solve this problem?
public ActionResult Index()
{
var searchResults = (from a in db.Courses
join b in db.Summary on
new { subject = a.subject, catalog = a.catalog, coursetitle = FormatCourseTitle(a.coursetitle) } equals
new { subject = b.Subject, catalog = b.Catalogno, coursetitle = b.CourseTitle } into ab
from b in ab.DefaultIfEmpty()
where a.Active == true
select new JoinModel
{
Courses = a,
Summary2020 = b
} ).ToList();
return View(searResults);
}
public class JoinModel
{
[Key]
public int Id { get; set; }
public Courselist Courses { get; set; }
public Contentsummary Summary { get; set; }
}
public string FormatCourseTitle(string courseTitle)
{
//find if last three characters are " or"
string[] words = courseTitle.Trim().ToLower().Split(' ');
int j = words.Count();
string tempStr = string.Empty;
if (words[j] == "or")
{
tempStr = courseTitle.Substring(0, courseTitle.Length - 3);
}
else
{
tempStr = courseTitle;
}
return tempStr;
}
You should use extension method as
public static class StringHelper
{
public static string FormatCourseTitle(this string courseTitle)
{
//find if last three characters are " or"
string[] words = courseTitle.Trim().ToLower().Split(' ');
int j = words.Count();
string tempStr = string.Empty;
if (words[j] == "or")
{
tempStr = courseTitle.Substring(0, courseTitle.Length - 3);
}
else
{
tempStr = courseTitle;
}
return tempStr;
}
}
Change query to
var searchResults = (from a in db.Courses
join b in db.Summary on
new { subject = a.subject, catalog = a.catalog, coursetitle = a.coursetitle.FormatCourseTitle() } equals
new { subject = b.Subject, catalog = b.Catalogno, coursetitle = b.CourseTitle } into ab
from b in ab.DefaultIfEmpty()
where a.Active == true
select new JoinModel
{
Courses = a,
Summary2020 = b
} ).ToList();
I find a way to add condition in linq query to solve this problem.
var searchResults = (from a in db.Courses
join b in db.Summary on
new { subject = a.subject, catalog = a.catalog, coursetitle = a.coursetitle.Trim().EndsWith(" or")?a.coursetitle.Substring(0,a.coursetitle.Length-3):a.coursetitle } equals
new { subject = b.Subject, catalog = b.Catalogno, coursetitle = b.CourseTitle } into ab
from b in ab.DefaultIfEmpty()
where a.Active == true
select new JoinModel
{
Courses = a,
Summary2020 = b
} ).ToList();

Check for but allow duplicates entries in the Db

My Db allows duplicate monuments, so the traditional method of checking for duplicates will not work. The user first inputs a monument name, then I run a check against the Db and if no duplicates found, great, allow the user to input the rest of the data. If one of more monuments with the same name are found, display a list of the monuments already in the Db. If this is truly a new monument with the same name, allow the user to input the new monument.
What I have so far:
[Authorize]
public ActionResult MonumentTitle(string battleRecordID, int callingRecordID)
{
ViewBag.monumentBattleRecID = battleRecordID; // ID of the battle
ViewBag.battleName = getBattleName(battleRecordID);
var vModel = new MonumentTitle();
vModel.BattleRecID = ViewBag.monumentBattleRecID;
vModel.BattleName = ViewBag.battleName;
vModel.CallingRecID = callingRecordID;
return View(vModel);
}
[HttpPost]
[Authorize]
public ActionResult MonumentTitle(MonumentTitle monumentTitle)
{
ViewBag.callingRecordID = monumentTitle.CallingRecID;
ViewBag.battleName = monumentTitle.BattleName;
ViewBag.MonumentName = monumentTitle.MonumentName;
var NmonumentTitle = monumentTitle;
ViewBag.battleName1 = NmonumentTitle.BattleName;
var List_monument = from s in db.Monuments
where (s.MonumentStatus == "A" &&
s.MonumentBattleRecID == monumentTitle.BattleRecID &&
s.MonumentName == monumentTitle.MonumentName
)
select s;
List_monument = List_monument.OrderBy(s => s.MonumentName);
var vModel = new MonumentTitleDuplicate();
vModel.MonumentTitle = NmonumentTitle;
vModel.Monument = List_monument.ToList();
if (vModel.Monument.Count == 0)
{
return RedirectToAction("MonumentCreate", new { battleRecord = vModel.MonumentTitle.BattleRecID, callingRecordID = vModel.MonumentTitle.CallingRecID, monumentName = vModel.MonumentTitle.MonumentName });
}
{
return RedirectToAction("MonumentTitleDuplicate", vModel );
}
}
Works for when there is not a duplicate. Where I run into a problem is trying to switch control to "MonumentTitleDuplicate" and pass the model.
[Authorize]
[HttpGet]
public ViewResult MonumentTitleDuplicate(MonumentTitleDuplicate monumentTitleDuplicate)
{
return View("MonumentTitleDuplicate", monumentTitleDuplicate);
}
[HttpPost]
[Authorize]
public ActionResult MonumentTitleDuplicate(MonumentTitle monumentTitle)
{
ViewBag.callingRecordID = monumentTitle.CallingRecID;
return RedirectToAction("MonumentCreate", new { battleRecord = monumentTitle.BattleRecID, callingRecordID = monumentTitle.CallingRecID, monumentName = monumentTitle.MonumentName });
}
[Authorize]
public ActionResult MonumentCreate(string battleRecord, int callingRecordID, string monumentName)
{
Got it -- needed to use TempData to pass the model to the new controller so:
[Authorize]
public ActionResult MonumentTitle(string battleRecordID, int callingRecordID)
{
ViewBag.monumentBattleRecID = battleRecordID; // ID of the battle
ViewBag.battleName = getBattleName(battleRecordID);
var vModel = new MonumentTitle();
vModel.BattleRecID = ViewBag.monumentBattleRecID;
vModel.BattleName = ViewBag.battleName;
vModel.CallingRecID = callingRecordID;
return View(vModel);
}
[HttpPost]
[Authorize]
public ActionResult MonumentTitle(MonumentTitle monumentTitle)
{
ViewBag.callingRecordID = monumentTitle.CallingRecID;
ViewBag.battleName = monumentTitle.BattleName;
ViewBag.MonumentName = monumentTitle.MonumentName;
var NmonumentTitle = monumentTitle;
ViewBag.battleName1 = NmonumentTitle.BattleName;
var List_monument = from s in db.Monuments
where (s.MonumentStatus == "A" &&
s.MonumentBattleRecID == monumentTitle.BattleRecID &&
s.MonumentName == monumentTitle.MonumentName
)
select s;
List_monument = List_monument.OrderBy(s => s.MonumentName);
var vModel = new MonumentTitleDuplicate();
vModel.MonumentTitle = NmonumentTitle;
vModel.Monument = List_monument.ToList();
if (vModel.Monument.Count == 0)
{
return RedirectToAction("MonumentCreate", new { battleRecord = vModel.MonumentTitle.BattleRecID, callingRecordID = vModel.MonumentTitle.CallingRecID, monumentName = vModel.MonumentTitle.MonumentName });
}
{
TempData["monumentTitleDuplicate"] = vModel;
return RedirectToAction("MonumentTitleDuplicate");
}
}
[Authorize]
public ActionResult MonumentTitleDuplicate()
{
MonumentTitleDuplicate monumentTitleDuplicate = TempData["MonumentTitleDuplicate"] as MonumentTitleDuplicate;
return View(monumentTitleDuplicate);
}
[HttpPost]
[Authorize]
public ActionResult MonumentTitleDuplicate(MonumentTitle monumentTitle)
{
ViewBag.callingRecordID = monumentTitle.CallingRecID;
return RedirectToAction("MonumentCreate", new { battleRecord = monumentTitle.BattleRecID, callingRecordID = monumentTitle.CallingRecID, monumentName = monumentTitle.MonumentName });
}
Probably have some cleanup work to do (like getting rid of the stuff where I was trying to use ViewBag), but does appear to be working.

MVC 4 Paging Searching

I have applied search method in my project but , I have also Action index()
and getting erorr. (The current request for action 'Index' on controller type 'AdultLiteracyTeachersController' is ambiguous between the following action methods:)
public ViewResult Index(string searchstring, string currentFilter, int? page)
{
if (searchstring != null)
{
page = 1;
}
else
{
searchstring = currentFilter;
}
ViewBag.CurrentFilter = searchstring;
var teachers = from r in db.AdulLiteracyTeachers select r;
if (!string.IsNullOrEmpty(searchstring))
{
teachers = teachers.Where(r => r.ALTName.ToUpper().Contains(searchstring.ToUpper()));
}
teachers = teachers.OrderBy(r => r.ALTName);
int pagesize = 10;
int pageNo = (page ?? 1);
return View(teachers.ToPagedList(pageNo, pagesize));
}
The other ActionResult.index()
public ActionResult Index()
{
var adulliteracyteachers = db.AdulLiteracyTeachers.Include(a => a.District);
return View(adulliteracyteachers.ToList());
}
Action result is used for calling all data how can I aplly in single index ?
Combine them:
public ViewResult Index(string searchstring, string currentFilter, int? page)
{
if (searchString == null && currentFilter == null && !page.HasValue)
{
// No parameters
var adulliteracyteachers = db.AdulLiteracyTeachers.Include(a => a.District);
return View(adulliteracyteachers.ToList());
}
// Regular code here down
if (searchstring != null)
{
page = 1;
}
else
{
searchstring = currentFilter;
}
ViewBag.CurrentFilter = searchstring;
var teachers = from r in db.AdulLiteracyTeachers select r;
if (!string.IsNullOrEmpty(searchstring))
{
teachers = teachers.Where(r => r.ALTName.ToUpper().Contains(searchstring.ToUpper()));
}
teachers = teachers.OrderBy(r => r.ALTName);
int pagesize = 10;
int pageNo = (page ?? 1);
return View(teachers.ToPagedList(pageNo, pagesize));
}

DevExpress GridView ExportToPdf doesn't export filtered data MVC

I have a webpage with gridview from Devexpress and i've implemented export to pdf. But somehow I don't get the current filter, order or group setting. I'm wondering if there is something wrong with how i set my setting in code or something since I've googled a lot at seems like those options should be handled automatically in ExportToPdf as long as you have rigth setting. My _GripPartial.cshtml:
#Html.DevExpress().GridView(TreeMenuTest.Controllers.LogViewController.GridViewSettings).Bind(TreeMenuTest.Controllers.LogViewController.DataSource).GetHtml()
_LogView.cshtml:
#using (Html.BeginForm("ExportToPDF", "LogView", FormMethod.Post))
{
<div id="buttonExport" class ="gridBtn">
<input type="submit" id ="ExportBtn" value="Export to pdf" />
</div>}
<div id="buttonReset" class ="gridBtn">
<input type="button" id ="ResetBtn" value="Reset Grid" onclick="javascript: ResetGrid()"/>
</div>
#Html.Action("Grid","LogView")
And finally LogViewController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using TreeMenuTest.Models;
using DevExpress.Web.Mvc;
using DevExpress.Web.ASPxGridView;
using System.Globalization;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxClasses;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using System.IO;
using System.Drawing.Printing;
namespace TreeMenuTest.Controllers
{
public class LogViewController : Controller
{
//
// GET: /LogView/
public static List<LoggingEvent> DataSource;
static GridViewSettings exportGridViewSettings;
public static GridViewSettings GridViewSettings
{
get
{
if (exportGridViewSettings == null)
exportGridViewSettings = GetGridViewSettings();
return exportGridViewSettings;
}
}
static GridViewSettings GetGridViewSettings()
{
GridViewSettings settings = new GridViewSettings();
settings.Name = "GridView";
settings.CallbackRouteValues = new { Controller = "LogView", Action = "Grid" };
settings.Width = Unit.Percentage(100);
settings.Theme = "BlackGlass";
settings.KeyFieldName = "Id";
settings.SettingsPager.Visible = true;
settings.Settings.ShowGroupPanel = true;
settings.Settings.ShowFilterRow = true;
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.SettingsPager.PageSize = 25;
settings.SettingsBehavior.ColumnResizeMode = ColumnResizeMode.Control;
settings.Settings.ShowHeaderFilterButton = true;
settings.SettingsPopup.HeaderFilter.Height = 200;
settings.SettingsExport.Landscape = true;
settings.SettingsExport.TopMargin = 0;
settings.SettingsExport.LeftMargin = 0;
settings.SettingsExport.RightMargin = 0;
settings.SettingsExport.BottomMargin = 0;
settings.SettingsExport.PaperKind = PaperKind.A4;
settings.SettingsExport.RenderBrick = (sender, e) =>
{
if (e.RowType == GridViewRowType.Data && e.VisibleIndex % 2 == 0)
e.BrickStyle.BackColor = System.Drawing.Color.FromArgb(0xEE, 0xEE, 0xEE);
};
settings.Columns.Add("Id");
settings.Columns.Add(column =>
{
column.FieldName = "Ts";
column.Settings.AutoFilterCondition = AutoFilterCondition.Like;
});
settings.Columns.Add("LogLevelText").Caption = "Level";
settings.Columns.Add("LoggerName");
settings.Columns.Add("Message");
settings.Columns.Add("ThreadName").Caption = "Thread";
settings.Columns.Add("UserName");
settings.Columns.Add("Domain");
settings.Columns.Add("ClassName");
settings.Columns.Add("FileName");
settings.Columns.Add("MethodName").Caption = "Method";
settings.Columns.Add("LineNumber").Caption = "Line";
settings.Columns.Add("LocalIP");
settings.Columns.Add("MachineName").Caption = "Machine";
settings.Columns.Add("UnikeName");
settings.Settings.ShowPreview = true;
settings.PreviewFieldName = "ExceptionString";
return settings;
}
public ActionResult Index()
{
return PartialView("_LogView");
}
public ActionResult Grid()
{
if (DataSource == null)
{
DataSource = GetAllEventsLast24h();
}
return PartialView("_GridPartial");
}
public ActionResult EmptyGrid()
{
DataSource = null;
return PartialView("_GridPartial");
}
public List<LoggingEvent> GetAllEventsLast24h() {
return GetEventsWithCommand("where Ts > '" + DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss") + "';");
}
public List<LoggingEvent> GetEventsOnDateTime(DateTime fromDate, DateTime toDate)
{
return GetEventsWithCommand("where Ts > '" + fromDate.ToString("yyyy-MM-dd HH:mm:ss") + "' AND Ts < '" + toDate.ToString("yyyy-MM-dd HH:mm:ss") + "';");
}
public List<LoggingEvent> GetEventsWithCommand(string where)
{
List<LoggingEvent> events = new List<LoggingEvent>();
SqlConnection myConnection = new SqlConnection("Data Source=xxx;user id=xxx;password=xxx;connection timeout=30");
myConnection.Open();
SqlDataReader myReader = null;
SqlCommand command = new SqlCommand("SELECT Id,Ts,LogLevel,LoggerName,Message,ThreadName,UserName,ExceptionString,Domain,ClassName,FileName,MethodName,LineNumber,LocalIP,MachinName,UnikeName from dbo.LoggingEvent " + where);
command.Connection = myConnection;
myReader = command.ExecuteReader();
while (myReader.Read())
{
events.Add(LoggingEvent.ReadEntityFromDbReader(myReader));
}
myConnection.Close();
return events;
}
[HttpPost]
public ActionResult ReloadGrid(string fromDate, string toDate)
{
DateTime fromDateTime;
DateTime toDateTime;
if (!string.IsNullOrEmpty(fromDate) && !string.IsNullOrEmpty(toDate)) // todo
{
fromDateTime = ParseStringToDate(fromDate);
toDateTime = ParseStringToDate(toDate);
}
else// No dates specified = get last 24 hours
{
toDateTime = DateTime.Now;
fromDateTime = toDateTime.AddHours(-24);
}
if (fromDateTime.CompareTo(toDateTime) > 0)
{
// from date grater then todate, change places
DateTime temp = toDateTime;
toDateTime = fromDateTime;
fromDateTime = temp;
}
DataSource = GetEventsOnDateTime(fromDateTime, toDateTime);
return PartialView("_LogView");
}
public DateTime ParseStringToDate(string datetxt)// todo this is copy froim treemenuviewcontroller, create utilsclass
{
const string dateformat = "dd.MM.yyyy HH:mm"; // jquery datepicker
const string dateformat2 = "yyyy-MM-dd HH:mm";// chrome TODO different formats with different location setting?
DateTime dateTime;
try //todo error handling!
{
dateTime = DateTime.ParseExact(datetxt, dateformat, CultureInfo.InvariantCulture);
}
catch
{
dateTime = DateTime.ParseExact(datetxt, dateformat2, CultureInfo.InvariantCulture);
}
return dateTime;
}
public ActionResult ExportToPDF()
{
var printable = GridViewExtension.CreatePrintableObject(GridViewSettings, DataSource);
PrintingSystem ps = new PrintingSystem();
PrintableComponentLink link1 = new PrintableComponentLink(ps);
link1.Component = printable;
link1.PrintingSystem.Document.AutoFitToPagesWidth = 1;
link1.Landscape = true;
CompositeLink compositeLink = new CompositeLink(ps);
compositeLink.Links.Add(link1);
compositeLink.CreateDocument();
using (MemoryStream stream = new MemoryStream())
{
compositeLink.PrintingSystem.ExportToPdf(stream);
WriteToResponse("filename", true, "pdf", stream);
}
ps.Dispose();
return Index();
}
void WriteToResponse(string fileName, bool saveAsFile, string fileFormat, MemoryStream stream)
{
string disposition = saveAsFile ? "attachment" : "inline";
Response.Clear();
Response.Buffer = false;
Response.AppendHeader("Content-Type", string.Format("application/{0}", fileFormat));
Response.AppendHeader("Content-Transfer-Encoding", "binary");
Response.AppendHeader("Content-Disposition",
string.Format("{0}; filename={1}.{2}", disposition, fileName, fileFormat));
Response.BinaryWrite(stream.GetBuffer());
Response.End();
}
}
}
Any clues?
Ps. Asking me why I don't write to DevExpress support is not helpful, so please just don't comment at all.
Check the How to export GridView rows and keep end-user modifications (such as sorting, grouping, filtering, selection) KB Article and make sure if all the steps are implemented.
After help for #Mikhail i fix the issue by putting #Html.Action("Grid","LogView") in the Html.BeginForm in _Log.View.cshtml like that:
<div id="buttonReset" class ="gridBtn">
<input type="button" id ="ResetBtn" value="Reset Grid" onclick="javascript: ResetGrid()"/>
</div>
#using (Html.BeginForm("ExportToPDF", "LogView", FormMethod.Post))
{
<div id="buttonExport" class ="gridBtn">
<input type="submit" id ="ExportBtn" value="Export to pdf" />
</div>
#Html.Action("Grid","LogView")}

How to convert Datatable to IList C#

While i build the Project, It have a error like this:
Server Error in '/' Application.
The model item passed into the dictionary is of type
'System.Data.DataTable', but this dictionary requires a model item of
type 'System.Collections.Generic.IList`1[TLayout.Models.DemoTable]'.
This is my Controller
public ActionResult Index()
{
var dm = new DemoTable();
string connstring = "Server=localhost;Port=5432;User Id=postgres;Password=123456;Database=test";
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
string sql = "select * from demo";
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
var demoid = dm.demoid.ToString();
var demoname = dm.demoname;
for (int i = 0; i < dt.Rows.Count; i++)
{
List<DataTable> dtb = new List<DataTable>();
demoid = dt.Rows[i]["demoid"].ToString();
demoname = dt.Rows[i]["demoname"].ToString();
dtb.Add(dt);
}
return View(dt);
}
This is my View, to show data to layout:
foreach (var item in Model)
{
fields.Add(Html.X().ModelField().Mapping(#item.demoid.ToString()).Name("grid-alarm"));
fields.Add(Html.X().ModelField().Mapping(#item.demoname.ToString()).Name("grid-check"));
}
var list = dt.AsEnumerable()
.Where(row => (int)row["demoid"] > 5)
.Select(row => new
{
demoid = Convert.ToInt32(row["demoid"]),
demoname = row["demoname"] != null ?
row["demoname"].ToString() :
String.Empty
}).ToList();
Or you can define class:
public class myClass
{
public int demoid;
public string demoname;
}
and then:
List<myClass> list = dt.AsEnumerable()
.Where(row => (int)row["demoid"] > 5)
.Select(row => new myClass
{
demoid = Convert.ToInt32(row["demoid"]),
demoname = row["demoname"] != null ?
row["demoname"].ToString() :
String.Empty
}).ToList<myClass>();

Resources