net mvc c#. I have created model for view. I can receive all rows from the table but when I try to pass value in method which is return list is not working
Here is my code
Controller class
public ActionResult Index()
{
TechnicianDBO db = new TechnicianDBO();
List<Technician> technicians = db.technicians.ToList();
return View(technicians);
}
[HttpPost]
public ActionResult Index(int Postcode)
{
TechnicianDBO db = new TechnicianDBO();
List<Technician> technicians = db.Jobtechnicians(Postcode).ToList();
return View(technicians);
}
Db class
public IEnumerable<Technician> Jobtechnicians(int postcode)
{
string connectionString = ConfigurationManager.ConnectionStrings["testConnect"].ConnectionString;
List<Technician> Jobtechnicians = new List<Technician>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spGetTechnicianByPostcode", con);
con.Open();
SqlParameter paramId = new SqlParameter();
paramId.ParameterName = "#postcode";
paramId.Value = postcode;
cmd.Parameters.Add(paramId);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Technician technician = new Technician();
technician.Id = Convert.ToInt32(dr["techId"]);
// technician.Username = dr["techUsername"].ToString();
technician.Firstname = dr["techFirstname"].ToString();
technician.Lastname = dr["techLastname"].ToString();
technician.LandlineNo = dr["landlineNo"].ToString();
technician.MobileNo = dr["mobileNo"].ToString();
technician.Address1 = dr["address1"].ToString();
technician.Address2 = dr["address2"].ToString();
technician.Postcode = Convert.ToInt32(dr["postcode"]);
technician.Email = dr["email"].ToString();
technician.Fax = dr["fax"].ToString();
technician.Profession = Convert.ToInt32(dr["ProfessionId"]);
Jobtechnicians.Add(technician);
}
return Jobtechnicians;
}
}
you need to give CommandType
SqlCommand cmd = new SqlCommand("spGetTechnicianByPostcode", con);
cmd.CommandType = CommandType.StoredProcedure;
and also when you call .ToString() you better check whether that column value null or not if that column allow null in your table
Related
Any suggestions would be awesome!
I keep getting a null value for my ClassID. When I add breakpoints, I can see the value ClassID being passed correctly, but when my program goes back to get a list I created, the ClassID returns null after stepping into that particular breakpoint. I believe my issue is in my controller, but I cant seem to find the issue.
Here is my DB file. The first dataset retrieves my ClassID from a stored procedure and my list below that returns the students in a particular ClassID
public DataSet GetClass(string ClassID)
{
ClassModel classes = new ClassModel();
SqlCommand com = new SqlCommand("sp_ABEAttendanceEnrollment", ABEAttendanceDB);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ClassID", ClassID);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds1 = new DataSet();
da.Fill(ds1);
return ds1;
}
public IEnumerable<ClassModel> ClassModel
{
get
{
string connectionString = ConfigurationManager.ConnectionStrings["ABEAttendanceDB"].ConnectionString;
List<ClassModel> students = new List<ClassModel>();
using (SqlConnection con = new SqlConnection(connectionString))
{
ClassModel classes = new ClassModel();
SqlCommand cmd = new SqlCommand("sp_ABEAttendanceEnrollment", ABEAttendanceDB);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ClassID", classes.ClassID);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
da.Fill(ds1);
ABEAttendanceDB.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
ClassModel student = new ClassModel();
student.ClassID = rdr["ClassID"].ToString();
student.SID = rdr["SID"].ToString();
student.FullName = rdr["FullName"].ToString();
students.Add(student);
}
ABEAttendanceDB.Close();
return students;
}
}
}
Here is my controller
public class ClassController : Controller
{
DAL.DB dblayer = new DAL.DB();
public ActionResult Class(ClassModel ClassModel)
{
DataSet ds1 = dblayer.GetClass(ClassModel.ClassID);
ViewBag.general = ds1.Tables;
ViewBag.Message = TempData["Message"];
DB classes = new DB();
List<ClassModel> students = dblayer.ClassModel.ToList();
return View();
}
}
Your DAL code is bit strange. Surely the GetClass method should return the IEnumerable<ClassModel>? Otherwise it just looks like you end up executing sp_ABEAttendanceEnrollment twice for no real reason. Putting a SQL query in a getter is rather unusual, to say the least. It's also not clear why you would need two copies of your data (one as a collection of DataTable via ViewBag.general and one as a List<ClassModel> via the students variable.
I'm not sure you need the ClassModel property on your DAL class at all. Just make the GetClass method read the data into an IEnumerable<Class> directly, and return it to the controller. Then you can return the list of students to the controller as the model for your view, something like this:
DAL:
public List<ClassModel> GetClass(string ClassID)
{
List<ClassModel> students = new List<ClassModel>();
SqlCommand cmd = new SqlCommand("sp_ABEAttendanceEnrollment", ABEAttendanceDB);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ClassID", ClassID);
ABEAttendanceDB.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
ClassModel student = new ClassModel();
student.ClassID = rdr["ClassID"].ToString();
student.SID = rdr["SID"].ToString();
student.FullName = rdr["FullName"].ToString();
students.Add(student);
}
ABEAttendanceDB.Close();
return students;
}
Controller:
public class ClassController : Controller
{
DAL.DB dblayer = new DAL.DB();
public ActionResult Class(ClassModel ClassModel)
{
ViewBag.Message = TempData["Message"];
List<ClassModel> students = dblayer.getClass(ClassModel.ClassID);
return View(students);
}
}
The view would then start with:
#model List<ClassModel>
I coded a web service connecting to MS-Sql server and getting the results from a stored procedure. My below code is getting only the first result of procedure, but I need all results in the response xml file. I think that I need to use data adapter, data reader, data fill, etc.. something like this. But I could not succeed. I would appreciate any help:
PS: Info.cs class already created.
[WebMethod]
public Info NumberSearch2(string no)
{
Info ourInfo = new Info();
string cs = ConfigurationManager.ConnectionStrings["DBBaglan"].ConnectionString;
using (SqlConnection Con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand(cmdText: "NumberSearch", connection: Con)
{
CommandType = CommandType.StoredProcedure
};
SqlParameter parameter = new SqlParameter
{
ParameterName = "#no",
Value = no
};
cmd.Parameters.Add(parameter);
Con.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataSet ds = new DataSet();
while (dr.Read())
{
ourInfo.PartNo = dr["PartNo"].ToString();
ourInfo.BrandNo = dr["BrandNo"].ToString();
ourInfo.Manufacturer = dr["Manufacturer"].ToString();
ourInfo.Country = dr["Country"].ToString();
ourInfo.ReferenceNo = dr["ReferenceNo"].ToString();
}
}
return ourInfo;
}
After #David 's recommendation:
[WebMethod]
//public Info NumberSearch2(string no)
public List<Info> NumberSearch2(string no)
{
Info ourInfo = new Info();
var ourInfos = new List<Info>();
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["DBBaglan"].ConnectionString;
using (System.Data.SqlClient.SqlConnection Con = new System.Data.SqlClient.SqlConnection(cs))
{
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(cmdText: "NumberSearch", connection: Con)
{
CommandType = System.Data.CommandType.StoredProcedure
};
System.Data.SqlClient.SqlParameter parameter = new System.Data.SqlClient.SqlParameter
{
ParameterName = "#no",
Value = no
};
cmd.Parameters.Add(parameter);
Con.Open();
System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
DataSet ds = new DataSet();
while (dr.Read())
{
var ourInfos = new Info();
ourInfo.PartNo = dr["PartNo"].ToString();
ourInfo.BrandNo = dr["BrandNo"].ToString();
ourInfo.Manufacturer = dr["Manufacturer"].ToString();
ourInfo.Country = dr["Country"].ToString();
ourInfo.ReferenceNo = dr["ReferenceNo"].ToString();
ourInfos.Add(ourInfo);
}
}
return ourInfos;
}
You're returning a single Info object. If you want a collection of them, return a List<Info> instead. Change the method signature:
public List<Info> NumberSearch2(string no)
Declare the object to return:
var ourInfos = new List<Info>();
Within your loop, add each record to the list:
while (dr.Read())
{
var ourInfo = new Info();
ourInfo.PartNo = dr["PartNo"].ToString();
ourInfo.BrandNo = dr["BrandNo"].ToString();
ourInfo.Manufacturer = dr["Manufacturer"].ToString();
ourInfo.Country = dr["Country"].ToString();
ourInfo.ReferenceNo = dr["ReferenceNo"].ToString();
ourInfos.Add(ourInfo);
}
And return the list:
return ourInfos;
So i need to pass a list from this method:
[WebMethod]
public List<SLA_ClassLibrary.SLA_Class.ReadAtm> ReadAtm()
{
var AtmReadList = new List<SLA_ClassLibrary.SLA_Class.ReadAtm>();
using (SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SLAdb"].ConnectionString))
{
using (Conn)
{
Conn.Open();
string SQLReadAtm = "Select * from ATM;";
SqlCommand ReadAtmCmd = new SqlCommand(SQLReadAtm, Conn);
SqlDataReader reader = ReadAtmCmd.ExecuteReader();
while (reader.Read())
{
AtmReadList.Add(new SLA_ClassLibrary.SLA_Class.ReadAtm
{
idatm = reader.GetInt32(reader.GetOrdinal("IDATM")),
District_Region = reader.GetString(reader.GetOrdinal("District_Region")),
Local = reader.GetString(reader.GetOrdinal("Local")),
IsUp = reader.GetBoolean(reader.GetOrdinal("IsUp"))
});
}
}
return AtmReadList;
}
}
to a website table in MVC, but i'm having problems on how to go about doing this.
I can't pass the "return AtmReadList" to a List<> so i have no idea on how to do this.
Any way to do this?
[WebMethod]
public List<reports> getMyReports( int user_id )
{
string cs = ConfigurationManager.ConnectionStrings["ReportDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("getAllReportsByUserID", con);
cmd.CommandType = CommandType.StoredProcedure;
List<reports> repers = new List<reports>();
//users[][] liser = new users[][];
SqlParameter user_id_parameter = new SqlParameter("#user_id", user_id);
cmd.Parameters.Add(user_id_parameter);
reports report = new reports();
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
report.id = Convert.ToInt32(reader["id"]);
report.title = reader["title"].ToString();
report.description = reader["description"].ToString();
report.anonymous = (bool)reader["anonymous"];
report.location = reader["location"].ToString();
report.status = reader["status"].ToString();
report.category = reader["category"].ToString();
report.date = (DateTime)reader["date"];
report.picture_url = reader["picture_url"].ToString();
report.admin_id = Convert.ToInt32(reader["admin_id"]);
repers.Add(report);
}
return repers;
}
}
I have the top function that calls the following stored procedure:
CREATE Proc [dbo].[getAllReportsByUserID]
#user_id int
as
Begin
Select
id,
title,
description,
anonymous,
location,
status,
category,
date,
picture_url,
admin_id
from reports
where user_id = #user_id
End
I have tested the procedure individually and it works fine. Yet, when I test the WebService created above I get a list with the last value duplicated along the whole list.
Can someone please help me figure out why do I get the same (last)value repeated over and over again?
By creating the report object before the loop and reusing it repeatedly, you insert a reference to that same object multiple times in your list.
You should create the report object inside your loop:
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
reports report = new reports();
report.id = Convert.ToInt32(reader["id"]);
report.title = reader["title"].ToString();
report.description = reader["description"].ToString();
report.anonymous = (bool)reader["anonymous"];
report.location = reader["location"].ToString();
report.status = reader["status"].ToString();
report.category = reader["category"].ToString();
report.date = (DateTime)reader["date"];
report.picture_url = reader["picture_url"].ToString();
report.admin_id = Convert.ToInt32(reader["admin_id"]);
repers.Add(report);
}
return repers;
I want to build a custom interface (a separate aspx page) to manage the data that is put into the webforms for marketeers (WFFM) database, and that for just one form. It must be possible to edit the data and select records with particular sortings and pagings. The database is configured to be SQLite.
Is this possible and recommended, or is it just plain xml that is saved into the WFFM database? And how should I go about it?
This is completely doable, though the select query to get data out of WFFM is a bit funky because everything is stored loose in one huge table called "field" with only a trail of GUIDs to tie the stored values back to what form they came from and what field.
Provided below is part of an Export to Excel utility I wrote for WFFM data. It builds a DataTable object from submitted form results. You could adapt it to some other structure without much work though.
public string connectionStringWFFM = "user id=sitecore_admin;password=xxx;Data Source=SitecoreDBServer.com;Database=Sitecore_WebForms";
protected DataTable BuildDataTable(Item formItem)
{
List<FormResult> formResults = FormResults(formItem.ID.Guid);
List<Field> distinctFields = DistinctFields(formItem.ID.Guid);
var dt = new DataTable();
dt.Columns.Add("Submission_DateTime", typeof (string));
foreach (Field field in distinctFields)
{
var dataColumn = new DataColumn("_" + field.id.ToString("N"), typeof (string));
dataColumn.Caption = field.name.Replace(" ", "_");
dt.Columns.Add(dataColumn);
}
foreach (FormResult formResult in formResults)
{
var connection = new SqlConnection();
connection.ConnectionString = connectionStringWFFM;
var command = new SqlCommand();
command.Connection = connection;
command.CommandText = "select fieldid, value from field where formid=#formid order by fieldid";
command.Parameters.Add("#formid", SqlDbType.UniqueIdentifier).Value = formResult.id;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
DataRow dataRow = dt.NewRow();
dataRow["Submission_DateTime"] = formResult.timestamp.ToString("MM/dd/yyyy HH:mm:ss");
while (reader.Read())
{
dataRow["_" + reader.GetGuid(0).ToString("N")] = reader.GetValue(1).ToString().Replace("<item>", "").Replace("</item>", "");
}
dt.Rows.Add(dataRow);
reader.Close();
connection.Close();
}
return dt;
}
public List<Field> DistinctFields(Guid formitemid)
{
var connection = new SqlConnection();
connection.ConnectionString = connectionStringWFFM;
var command = new SqlCommand();
command.Connection = connection;
command.CommandText = "select distinct fieldid from field where formid in (select id from form where formitemid=#formitemid) order by fieldid";
command.Parameters.Add("#formitemid", SqlDbType.UniqueIdentifier).Value = formitemid;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
var results = new List<Field>();
int count = 0;
while (reader.Read())
{
var field = new Field();
field.id = reader.GetGuid(0);
Database database = Factory.GetDatabase("master");
Item i = database.GetItem(new ID(field.id));
if (i != null && i.DisplayName != null)
{
field.name = i.DisplayName;
}
else
{
field.name = "Field" + count;
}
results.Add(field);
count += 1;
}
reader.Close();
connection.Close();
return results;
}
public List<FormResult> FormResults(Guid formitemid)
{
var connection = new SqlConnection();
connection.ConnectionString = connectionStringWFFM;
var command = new SqlCommand();
command.Connection = connection;
command.CommandText = "select id, timestamp from form where formitemid=#formitemid";
command.Parameters.Add("#formitemid", SqlDbType.UniqueIdentifier).Value = formitemid;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
var results = new List<FormResult>();
while (reader.Read())
{
var result = new FormResult();
result.id = reader.GetGuid(0);
result.timestamp = reader.GetDateTime(1);
results.Add(result);
}
reader.Close();
connection.Close();
return results;
}
public class FormResult
{
public Guid id { get; set; }
public DateTime timestamp { get; set; }
}
public class Field
{
public Guid id { get; set; }
public string name { get; set; }
}