How can I pass DataTable to view as JSON/XML code? - c#

I am new to the .NET environment and trying to write a simple MVC application to read student data and display it to the end user. I have connected to a database using SQLOLEDB, the code of which I have pasted below. The data obtained from the query was stored in a variable of the type DataTable. Now I want to see the content of the query result in the form of a JSON output for which I have a faintest idea that I have to create a new controller. But I am not able to proceed beyond this point.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
namespace Database.model
{
public class student
{
public int id { get; set; }
public string name { get; set; }
private string age { get; set; }
public DataTable GETSQLServerData()
{
//Connect
var _connectionobject = new SqlConnection();
_connectionobject.ConnectionString = #"Provider=SQLOLEDB;Data Source=PHYSICS\SQLEXPRESS;Persist Security Info=true;Initial Catalog=master;Integrated Security=True; provider = SQLOLEDB;";
_connectionobject.Open();
//Command
var _commandObject = new SqlCommand();
_commandObject.CommandText = "select * from dbo.tblStudent";
//Execute
_commandObject.ExecuteReader();
//Data
var _dataReader = _commandObject.ExecuteReader();
DataTable obj2 = new DataTable();
obj2.Load(_dataReader);
_connectionobject.Close();
return obj2;
}
}
}
I would be really grateful if anyone could help me in this regard

You can convert the datatable object into a POCO object
How do I convert a datatable into a POCO object in Asp.Net MVC?
then return that POCO object back to the browser.
The best practice would be to create a class that will hold the student data and return that class object instead of the data table like so.
// you student model class
public class Student
{
// public properties of student...
}
In your data access class populate this student object list and return to the MVC action method.
//then in your MVC action method
IEnumerable<Student> students = GETSQLServerData();
return this.Json(students , JsonRequestBehavior.AllowGet);
A few points about your code:
1- Avoid using sql statement in your C# code, switch to stored
procedure.
2- Use Data Model layer and create Student class to define student
model.
3- Use Data acccess layer to call SQL Stored proc
4- Inject dependencies to avoid tightly coupled classes.
Hope this helps!

Related

c# filter database results using EF similar to SQL WHERE Clause

I've connected to my database using Entity Framework and am building my first MVC app for use in a web page.
I can get the controller to populate public strings in my models with no problem... the issue I'm having is that I can't figure out how to filter responses from my database.
I expect to have only one item returned which I will display in the view with #Model.BusinessUnit
Here's my Model Class for the database table:
public partial class TBL_Wholesale_UWS_BusinessUnits
{
public int PrimaryID { get; set; }
public string BusinessUnit { get; set; }
public string Status { get; set; }
}
Here's what I have in my controller:
public ActionResult test(int PrimaryID)
{
var testing = new TBL_Wholesale_UWS_BusinessUnits();
// maybe putting new is the wrong thing to do as that would be wiping the class? IDK
return View(testing);
}
As you can see, the PrimaryID is passed to the controller via the querystring and this is recognised without issue, but I'm at a loss as to where to add the filter, I assumed it would be something like...
var testing = TBL_Wholesale_UWS_BusinessUnits.Where(TBL_Wholesale_UWS_BusinessUnits.PrimaryID = PrimaryID);`
but Visual Studio is telling me in no uncertain terms that this this wrong.
Had this been classic asp I would have just made a record set and used the where clause in SQL, but as this is built with the Entity Framework to do my connecting I don't really know where to start.
Any help would be greatly appreciated.
If you are only trying to return that one specific object to the view.. then you need to find that int PrimaryID in the database and retrieve that specific record.
What you are doing is simply creating a new instance of the TBL_Wholesale_UWS_BusinessUnits class which is empty.
Try this:
public ActionResult test(int PrimaryID)
{
var testing = db.TableName.Find(PrimaryID);
// db = Whatever the variable holding your connection string is.. maybe DbContext
// TableName = Whatever table in your database that holds the record you want
// This will return the specific object that you are looking for
return View(testing);
}
I hope this helps!

Web Method not returning list?

I have a .aspx page which I would like my WebMethod to return a List so I can call it from a jQuery ajax call and get a JSON type response... Here is my code but it just returns a blank page?
Any help would be great
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
namespace Test.webservices.mainGrid
{
public partial class staffTreeView : System.Web.UI.Page
{
[WebMethod()]
public static List<Staff> GetStaff()
{
try
{
List<Staff> staff = new List<Staff>();
// HttpCookie _userinfo = HttpContext.Current.Request.Cookies["userinfo"];
string connectionstring = ConfigurationManager.ConnectionStrings["TestProduction"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionstring);
string sql = "sd_STAFFTREEVIEW";
SqlCommand command = new SqlCommand(sql, connection);
command.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
staff.Add(new Staff()
{
id = dr.GetString(dr.GetOrdinal("id")),
NAME = dr.GetString(dr.GetOrdinal("NAME")),
PARENT = dr.GetString(dr.GetOrdinal("PARENT")),
VALUE = dr.GetString(dr.GetOrdinal("VALUE")),
VALUETYPE = dr.GetString(dr.GetOrdinal("VALUETYPE"))
});
}
dr.Close();
return staff;
}
catch (Exception ex)
{
throw new System.Exception("No Data Returned:" + ex.Message);
}
}
public class Staff
{
public string id { get; set; }
public string NAME { get; set; }
public string PARENT { get; set; }
public string VALUE { get; set; }
public string VALUETYPE { get; set; }
}
}
}
I would try changing the return type to a string and returning a json serialized string of the object.
Like this
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(staff);
return strJSON;
create a WCF service instead of a page !
and consider returning an Array instead of a generic list Staff[]
Few things to check.
Do you need to enable the session : Services.WebMethod(EnableSession:=True)
Are you using the correct method name ( check spelling). Better , could you post the code for ajax call ?
If you call the web method from somewhere else like code behind , is it giving you the correct result?
I would recommend that you use a WebAPI controller for this task, can be used in a web forms application, just wire up the routing in application_start
It will save you some pain and make your life easier
http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-aspnet-web-forms
I suspect that your ajax call is not happening.
Provided you are sure that your list is not empty, make sure that you have set the dataType and contentType of your ajax request to json and "application/json" respectively.
If you are using a script manager control make sure Enablepagemethods is set to true.
finally you can try setting a break point in your error callback to find if there are any serialisation errors.if so, you can try to serialise the LIST to JSON using JavaScriptSerializer and return the result as String

Pass a list of objects to a web service

I have a DataObjects class that contains a UserEmail object that contains an int (EmailID) and a string (EmailAddress).
Within a C# .net application, if I want to display a list of email addresses - I create and populate a list of UserEmail objects.
List<DataObjects.UserEmails> myUserEmailsList = new List<DataObjects.UserEmails>();
And use it as a datasource for whatever control I happen to be using.
I need to pass that list to a web service. I can't see how to do this. If the other party writes a web service with a method that takes a list as a parameter - fine, I can call the web service and pass my list. But how will they be able to extract the data from the list - without having access to the classes that created the objects in the list?
Is there a way of looping through a list of objects without knowing what the data structure of the object is?
When you are consuming their web service, you have to conform to their data structures. You take your UserEmail object data, and would convert it to the object their service is expecting.
If you're using a service where it's just needing the data as get or post data, you'll have to use whatever keys they are requiring. So they might take the email address using a key of "email" instead of your property name of "EmailAddress"
here a sample to pass list object to your webservice
<%#WebService Language="c#" class="CustomObjectArrayWS"%>
using System;
using System.Collections;
using System.Web.Services;
using System.Xml.Serialization;
public class CustomObjectArrayWS
{
[WebMethodAttribute]
[XmlInclude(typeof(Address))]
public ArrayList GetAddresses ()
{
ArrayList al = new ArrayList();
Address addr1 = new Address("John Smith", "New York",12345);
Address addr2 = new Address("John Stalk", "San Fransisco", 12345);
al.Add(addr1);
al.Add(addr2);
return al;
}
}
// Custom class to be added to the collection to be passed in //and out of the service
public class Address
{
public string name;
public string city;
public int zip;
// Default ctor needed by XmlSerializer
public Address()
{
}
public Address(string _name, string _city, int _zip )
{
this.name = _name;
this.city = _city;
this.zip = _zip;
}
}
see http://www.programmersheaven.com/2/XML-Webservice-FAQ-Pass-Array-Of-Custom-Objects

how to create a custom JSON in C# and what should the return value be?

i want create a custom json data from the mssql 2008 results so that my iPhone could consume it.
i can consume json websites like this without a problem:
json link
the format could look like this:
Place: New York
Hotel: Widget Hotel
Telephone: 0305525253
which format should i return to consume it on the iPhone? an array a string, dictionary? i don't know
EDIT: here is my code:
namespace WebService1
{
public class LandHelper
{
internal static string[] Land()
{
List<string> landObject = new List<string>();
using (SqlConnection con = new SqlConnection(#"Data Source=Localhost\SQLEXPRESS;Initial Catalog=BOOK-IT-V2;Integrated Security=true;"))
using (SqlCommand cmd = new SqlCommand(#"SELECT BEZEICHNUNG FROM LAND", con))
{
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (rdr["BEZEICHNUNG"] != DBNull.Value)
{
landObject.Add(rdr["BEZEICHNUNG"].ToString());
}
}
}
}
return landObject.ToArray();
}
}
}
i tried this but i don't know how to add a key to the values i get from the database.
i think it would be easier when i create a custom json format .
Just Return a List like
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public List<StandortHelper.REGION> LAND()
{
return StandortHelper.LAND();
}
You can return easy a JSON-FORMAT
Okay, if I've understood this correctly what you're trying to do is stringify a collection of objects to JSON, and then read them in your iPhone app. I'm assuming you're asking for how to convert from object-to-JSON, and that you've already covered JSON-to-object. I'll cover object-to-JSON here.
What you'll need to do is create a class that contains all of the information you need in your JSON file, like so.
public class Location
{
public string Place { get; set; }
public string Hotel { get; set; }
public string Telephone { get; set; }
}
Now, inside your database reader statement, you'll want to construct a List<Location>, and then add each Location to this list. Once you've done this, you'll easily be able to convert the collection to JSON using the JSON.NET framework... which makes converting objects to JSON as easy as:
// "locations" is the name of the collection
JsonConvert.SerializeObject(locations);
JSON .NET Documentation
Hope this helps. :)

GridControl (GridView) returns no rows

EDIT: Fixed.. I believe the problem was fixed by going to Add New Item -> Persistent Classes 11.2 and adding a new persistent class through the wizard. Then I just copied the code from that and put it in my Form1 code. Works!
I was following this page very closely: http://documentation.devexpress.com/#WindowsForms/CustomDocument3265
I tried both ways of getting a gridcontrol setup to show records from a SQL Server database, neither worked. Both (when I ran the program) returned the columns but no rows. I am positive I have the correct SQL server name, database name and table name. Searching Google seems to return "how to get the program to show a message that says 'no rows found'" i.e. nothing useful. Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;
using DevExpress.Xpo.Metadata;
using DevExpress.XtraGrid;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Generate the connection string to the AdventureWorks database on local SQL Server.
XpoDefault.ConnectionString =
MSSqlConnectionProvider.GetConnectionString("dsd-sql3", "PH");
// Create a Session object.
Session session1 = new Session(XpoDefault.GetDataLayer(XpoDefault.ConnectionString, AutoCreateOption.None));
// Create an XPClassInfo object corresponding to the Person_Contact class.
XPClassInfo classInfo = session1.GetClassInfo(typeof(Call));
// Create an XPServerCollectionSource object.
XPServerCollectionSource xpServerCollectionSource1 =
new XPServerCollectionSource(session1, classInfo);
xpServerCollectionSource1.Reload();
// Create a grid control.
GridControl gridControl1 = new GridControl();
gridControl1.Dock = DockStyle.Fill;
this.Controls.Add(gridControl1);
// Enable server mode.
gridControl1.ServerMode = true;
// Bind the grid control to the data source.
gridControl1.DataSource = xpServerCollectionSource1;
}
}
[Persistent("dbo.CallLog")]
public class Call : XPLiteObject
{
public Call(Session session) : base(session) { }
[Key, DevExpress.Xpo.DisplayName("Oid")]
public string Oid;
//public string Title;
[DevExpress.Xpo.DisplayName("FirstName")]
public string FirstName;
[DevExpress.Xpo.DisplayName("MiddleName")]
public string MiddleName;
[DevExpress.Xpo.DisplayName("LastName")]
public string LastName;
[DevExpress.Xpo.DisplayName("Email")]
public string Email;
//public string Phone;
}
}
My coworker said that its possible the data is being loaded from the DB but not linked, and he wasn't sure how to fix it...
Any help is greatly appreciated. Thanks.

Categories