I have a multi-select control whereby I need to commit all items selected to SQL Server table. When I submit the form only 1 item is getting committed even though when i inspect using Step Debugger all the selected values are indeed populated in variable employeees4 (attached image). i have observed that only the first item in the selection is getting committed. Any help on what i could possibly be missing?
Please note that i have used slightly different variable name in attached image has i.e year instead of employeees4, but the code is the same .
I am getting selected items as below :
[HttpPost]
public ActionResult NewOverTimeRequest(FormCollection formcollection)
{
Models.Employee.OverTimeRequest request = new Models.Employee.OverTimeRequest();
try
{
var batch = new OvertimeBatch();
request.employees = GetEmployees();
request.EmployeeNumber = new string[] { Convert.ToString(formcollection["EmployeeNumber"]) };
var employeees1= request.EmployeeNumber.Split(',');
string[] employeees2 = employeees.SingleOrDefault().ToArray();
string employeees3 = Helpers.ConvertStringArrayToString( employeees2);
string[] employeees4 =employeees3.Split(new char[] { ',' });
if (ModelState.IsValid)
{
foreach ( string emp in employeees4)
{
using (SqlConnection conn = new SqlConnection(Helpers.DatabaseConnect))
{
SqlCommand cmd = new SqlCommand("SubmitOverTime", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpNum", emp);
cmd.Parameters.AddWithValue("#DateDone", DateTime.Now);
conn.Open();
cmd.ExecuteNonQuery();
}
}
return RedirectToAction("OverTime");
}
catch (Exception ex)
{
ViewBag.ErrorMessage = ex.Message;
return View(request);
}
return RedirectToAction("OverTime");
}
}
Model :
[Required]
[Display(Name = "Employee ")]
public string[] EmployeeNumber { get; set; }
public Employee Employee { get; set; }
public String DisplayName { get; set; }
public IEnumerable<SelectListItem> employees { get; set; }
Try changing you If condition to below.
if (ModelState.IsValid)
{
using(SqlConnection conn = New SqlConnection(Helpers.DatabaseConnect))
{
conn.Open();
SqlCommand cmd = New SqlCommand("SubmitOverTime", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmpNum", SqlDbType.varchar(max));
cmd.Parameters.Add("#DateDone", SqlDbType.DateTime);
foreach(String emp In employeees4)
{
cmd.Parameters["#FixtureId"].Value=emp;
cmd.Parameters["#FixtureId"].Value= DateTime.Now;
cmd.ExecuteNonQuery();
}
}
return RedirectToAction("OverTime");
}
Related
I am trying to iterate through an SQL query and set the objects parameters to particular values. The only value that seems to be functioning correctly is the workpack.JobCardIDs, as I can implement a foreach loop to display the results. If I try to set a Label's Text property to a workpack.WorkPackTitle for example, it will display a blank even though the database value is something for every line.
I am fairly new to the OOP so not entirely sure if there is something I am missing that's fundamental.
public class WorkPack
{
public int ID { get; set; }
public string WorkPackNumber { get; set; }
public string WorkPackTitle { get; set; }
public string WorkPackDescription { get; set; }
public Boolean IFC { get; set; }
public string SPA { get; set; }
public string Writer { get; set; }
public string Organization { get; set; }
public List<int> JobCardIDs { get; set; }
public int JobCard { get; set; }
}
public static WorkPack PopulateWorkPackObject(WorkPack workpack, int workPackID)
{
string ConnectionString = ConfigurationManager.ConnectionStrings["vmdatamanagerConnectionString"].ConnectionString;
string sqlCall = "I HAVE REMOVED CALL BUT VERIFIED IT FUNCTIONS (SELECT columns FROM workpackdatabase where workpackname = x";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlCall, con))
{
cmd.Connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (reader.IsDBNull(reader.GetOrdinal("PARAM1")) == false)
workpack.WorkPackNumber = (reader.GetString(reader.GetOrdinal("PARAM1")));
if (reader.IsDBNull(reader.GetOrdinal("PARAM2")) == false)
workpack.WorkPackTitle = reader.GetString(reader.GetOrdinal("PARAM2"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM3")) == false)
workpack.WorkPackDescription = reader.GetString(reader.GetOrdinal("PARAM3"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM4")) == false)
workpack.IFC = reader.GetBoolean(reader.GetOrdinal("PARAM4"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM5")) == false)
workpack.SPA = reader.GetString(reader.GetOrdinal("PARAM5"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM6")) == false)
workpack.Writer = reader.GetString(reader.GetOrdinal("PARAM6"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM7")) == false)
workpack.Organization = reader.GetString(reader.GetOrdinal("PARAM7"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM8")) == false)
jobCardIDs.Add(reader.GetInt32(reader.GetOrdinal("PARAM8")));
}
workpack.JobCardIDs = jobCardIDs;
return workpack;
}
}
}
}
Looks like you never create a local instance of your jobCardIDs List. You'll want to do this just inside your ExecuteReader block. See below. GL
public static WorkPack PopulateWorkPackObject(WorkPack workpack, int workPackID)
{
string ConnectionString = ConfigurationManager.ConnectionStrings["vmdatamanagerConnectionString"].ConnectionString;
string sqlCall = "I HAVE REMOVED CALL BUT VERIFIED IT FUNCTIONS (SELECT columns FROM workpackdatabase where workpackname = x";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlCall, con))
{
cmd.Connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
List<int> jobCardIDs = new List<int>(); //<--***THIS IS THE LINE YOU NEED TO ADD***
while (reader.Read())
{
if (reader.IsDBNull(reader.GetOrdinal("PARAM1")) == false)
workpack.WorkPackNumber = (reader.GetString(reader.GetOrdinal("PARAM1")));
if (reader.IsDBNull(reader.GetOrdinal("PARAM2")) == false)
workpack.WorkPackTitle = reader.GetString(reader.GetOrdinal("PARAM2"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM3")) == false)
workpack.WorkPackDescription = reader.GetString(reader.GetOrdinal("PARAM3"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM4")) == false)
workpack.IFC = reader.GetBoolean(reader.GetOrdinal("PARAM4"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM5")) == false)
workpack.SPA = reader.GetString(reader.GetOrdinal("PARAM5"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM6")) == false)
workpack.Writer = reader.GetString(reader.GetOrdinal("PARAM6"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM7")) == false)
workpack.Organization = reader.GetString(reader.GetOrdinal("PARAM7"));
if (reader.IsDBNull(reader.GetOrdinal("PARAM8")) == false)
jobCardIDs.Add(reader.GetInt32(reader.GetOrdinal("PARAM8")));
}
workpack.JobCardIDs = jobCardIDs;
return workpack;
}
}
}
}
The previous answers given by the community did not fix the issue, although I did put that extra snippet it.
The issue was when the objects were being created and passed between post backs. The object would be relevant on selection of the job card tab but once the page loaded there was no code to rebuild that instance.
Adding
Object foo = new Object();
in the page_Load() and rebuilding fixed the issue. If anyone has any suggestions on how to keep an instance alive I am all for hearing it. I think ViewState() and also Session[] were applicable methods for doing so.
Error 1
'UserWcfService.userService' does not implement interface member
'UserWcfService.IuserService.Getuserdetails()'.
'UserWcfService.userService.Getuserdetails()' cannot implement an
interface member because it is not
public. C:\Users\ravi\Documents\Visual Studio
2013\Projects\wcfservices\UserWcfService\UserWcfService\userService.svc.cs 16 18 UserWcfService
userservice.svc.cs code:
namespace UserWcfService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "userService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select userService.svc or userService.svc.cs at the Solution Explorer and start debugging.
public class userService : IuserService
{
public string str = ConfigurationManager.ConnectionStrings["connstring"].ToString();
List<usertype> Getuserdetails()
{
List<usertype> userdetails=new List<usertype>();
SqlConnection conn = new SqlConnection(str);
{
conn.Open();
SqlCommand cmd = new SqlCommand("spgetdata", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for(int i=0; i<dt.Rows.Count; i++)
{
usertype objinfo = new usertype();
objinfo.name = Convert.ToString(dt.Rows[i]["name"]);
objinfo.gender = Convert.ToString(dt.Rows[i]["gender"]);
objinfo.dateofbirth = Convert.ToDateTime(dt.Rows[i]["dateofbirth"]);
objinfo.address = Convert.ToString(dt.Rows[i]["address"]);
objinfo.contactno = Convert.ToInt32(dt.Rows[i]["contactno"]);
objinfo.mailid = Convert.ToString(dt.Rows[i]["mailid"]);
userdetails.Add(objinfo);
}
}
conn.Close();
}
return userdetails;
}
public string newuser(usertype user)
{
string strmessage;
SqlConnection conn = new SqlConnection(str);
{
conn.Open();
SqlCommand cmd = new SqlCommand("spinsert", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#C_Users_Name", user.name);
cmd.Parameters.AddWithValue("#C_Users_Gender", user.gender);
cmd.Parameters.AddWithValue("#lC_Users_DOB", user.dateofbirth);
cmd.Parameters.AddWithValue("#C_Users_Address", user.address);
cmd.Parameters.AddWithValue("#C_Users_ContactNo", user.contactno);
cmd.Parameters.AddWithValue("#C_Users_MailID", user.mailid);
//cmd.Parameters.AddWithValue("#C_Users_RegisteredDate", userinfo.date);
int result = cmd.ExecuteNonQuery();
if(result==1)
{
strmessage = user.name + "details inserted succesfully";
}
else
{
strmessage = user.name + "Details not inserted";
}
conn.Close();
}
return strmessage;
}
}
}
and IUserService code:
namespace UserWcfService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IuserService" in both code and config file together.
[ServiceContract]
public interface IuserService
{
[OperationContract]
List<usertype> Getuserdetails();
[OperationContract]
string newuser(usertype user);
}
[DataContract]
public class usertype
{
[DataMember]
public string name { get; set; }
[DataMember]
public string gender { get; set; }
[DataMember]
public DateTime dateofbirth { get; set; }
[DataMember]
public string address { get; set; }
[DataMember]
public int contactno { get; set; }
[DataMember]
public string mailid { get; set; }
[DataMember]
public DateTime date { get; set; }
}
}
All interface methods are by default public therefore your class which dervies interface needs to be public as well.
A good way to see what you are doing wrong here is to right click on the IuserService in
public class userService : IuserService
go to implement interface -> implement interface explicitly
this will create the stub methods that are implementing your interface. you can either drop your code into those or you could adjust the methods that you have appropriately
Here is an example which built I derived using the method I described above
public class userService : IuserService
{
public string str = ConfigurationManager.ConnectionStrings["connstring"].ToString();
List<usertype> IuserService.Getuserdetails()
{
List<usertype> userdetails = new List<usertype>();
SqlConnection conn = new SqlConnection(str);
{
conn.Open();
SqlCommand cmd = new SqlCommand("spgetdata", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
usertype objinfo = new usertype();
objinfo.name = Convert.ToString(dt.Rows[i]["name"]);
objinfo.gender = Convert.ToString(dt.Rows[i]["gender"]);
objinfo.dateofbirth = Convert.ToDateTime(dt.Rows[i]["dateofbirth"]);
objinfo.address = Convert.ToString(dt.Rows[i]["address"]);
objinfo.contactno = Convert.ToInt32(dt.Rows[i]["contactno"]);
objinfo.mailid = Convert.ToString(dt.Rows[i]["mailid"]);
userdetails.Add(objinfo);
}
}
conn.Close();
}
return userdetails;
}
public string newuser(usertype user)
{
string strmessage;
SqlConnection conn = new SqlConnection(str);
{
conn.Open();
SqlCommand cmd = new SqlCommand("spinsert", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#C_Users_Name", user.name);
cmd.Parameters.AddWithValue("#C_Users_Gender", user.gender);
cmd.Parameters.AddWithValue("#lC_Users_DOB", user.dateofbirth);
cmd.Parameters.AddWithValue("#C_Users_Address", user.address);
cmd.Parameters.AddWithValue("#C_Users_ContactNo", user.contactno);
cmd.Parameters.AddWithValue("#C_Users_MailID", user.mailid);
//cmd.Parameters.AddWithValue("#C_Users_RegisteredDate", userinfo.date);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
strmessage = user.name + "details inserted succesfully";
}
else
{
strmessage = user.name + "Details not inserted";
}
conn.Close();
}
return strmessage;
}
I am retrieving records from store procedure, but it does not bind data into view.
Here is ModelContext class:
namespace MyTesting.Models
{
public class TvSerialDB
{
public static string constr = ConfigurationManager.ConnectionStrings["TvSerialContext"].ConnectionString;
SqlConnection con;
SqlCommand cmd;
public IEnumerable<TVSerialByGroup> tvserialgroupby(string serialname)
{
List<TVSerialByGroup> tvserials = new List<TVSerialByGroup>();
using (con = new SqlConnection(constr))
{
cmd = new SqlCommand("pSerialListGroupBySerialName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#SerialName", SqlDbType.VarChar, 100).Value = serialname;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
TVSerialByGroup tvs = new TVSerialByGroup();
tvs.Series_Name = sdr["Series_Name"].ToString();
tvs.Image_Url_Big = sdr["Image_Url_Big"].ToString();
tvs.Season_No = sdr["Season_No"].ToString();
tvs.TotalEpisode = sdr["TotalEpisode"].ToString();
}
}
return tvserials;
}
}
}
Here is ModelClass:
namespace MyTesting.Models
{
public class TVSerialByGroup
{
public string Series_Name { get; set; }
public string Season_No { get; set; }
public string Image_Url_Big { get; set; }
public string TotalEpisode { get; set; }
}
}
Here is controller class:
public ActionResult ListAllSeason(string serial)
{
try
{
TvSerialDB tvcon = new TvSerialDB();
List<TVSerialByGroup> tv = tvcon.tvserialgroupby(serial).ToList();
return View(tv);
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
When i run this application it does not display any record nor it gives error.
When i debug this code through breakpoint it returns rows into store procedure but in views it does not bind data.
You not adding your model instances to the collection.
while (sdr.Read())
{
TVSerialByGroup tvs = new TVSerialByGroup();
tvs.Series_Name = sdr["Series_Name"].ToString();
tvs.Image_Url_Big = sdr["Image_Url_Big"].ToString();
tvs.Season_No = sdr["Season_No"].ToString();
tvs.TotalEpisode = sdr["TotalEpisode"].ToString();
tvserials.Add(tvs); // add this
}
Side note: Since your initializing List<TVSerialByGroup>, you can make your method public List<TVSerialByGroup> tvserialgroupby(string serialname) and then you do not need .ToList(); in the ActionResult method.
I want to execute a insert query in mvc4 on action button,
i have the below action method in my controller
[HttpPost]
public ActionResult Index(QuestionBank model)
{
try
{
using (var db = new AdminContext())
{
db.Questions.Add(model);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I have related model
public class QuestionBank
{
[Key]
////[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public string question { get; set; }
}
As we do in simple asp.net application i want to execute that stored procedure on action button.
I don't know whether my approach is right, but please guide me on this.
I'm assuming that you wan't to use the stored procedure approach to execute inserting a question into the database.
[HttpPost]
public ActionResult Index(QuestionBank model)
{
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("[dbo].[sp_addQuestion]", conn) { CommandType = CommandType.StoredProcedure, CommandTimeout = 0 };
cmd.Parameters.Add(new SqlParameter("question", model.question) { SqlDbType = SqlDbType.Structured });
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
cmd.ExecuteNonQuery();
}
//using (var db = new AdminContext())
//{
// db.Questions.Add(model);
// db.SaveChanges();
//}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Here's the corresponding stored procedure
ALTER PROCEDURE [dbo].[sp_addQuestion]
#question nvarchar(255)
AS
BEGIN
INSERT INTO [dbo].[QuestionBank] (Question)
VALUES (#question)
RETURN ##ERROR;
END
I have listbox
#Html.ListBox("lais", new SelectList(Model.lista, "Value", "Text"), new {#class = "mylistbox"});
Here am getting list data but not binding to listbox (list items value )
This is my action method
public ActionResult PrintRFIDTag()
{
Print p =new Print();
p.lista = GetList();
return View(p);
}
public SelectList GetList()
{
System.Management.ManagementScope objMS =
new System.Management.ManagementScope(ManagementPath.DefaultPath);
objMS.Connect();
List<SelectListItem> items = new List<SelectListItem>();
SelectQuery objQuery = new SelectQuery("SELECT * FROM Win32_Printer");
ManagementObjectSearcher objMOS = new ManagementObjectSearcher(objMS, objQuery);
System.Management.ManagementObjectCollection objMOC = objMOS.Get();
foreach (ManagementObject Printers in objMOC)
{
if (Convert.ToBoolean(Printers["Network"])) // ALL NETWORK PRINTERS.
{
var emptyItem = new SelectListItem()
{
Value = Printers["Name"].ToString(),
Text = "00"
};
items.Add(emptyItem);
}
}
SelectList objselectlist = new SelectList(items,"Value");
return objselectlist;
}
}
Here is my model class
public class Print
{
public SelectList lista { get; set; }
public string Name { get; set; }
}
Returning from view but not binding to listbox
Your help will be appropriated
try this:
#Html.ListBoxFor(m=>m.lista ,Model.lista) and change line SelectList objselectlist = new SelectList(items,"Value"); to this: SelectList objselectlist = new SelectList(items,"Value","Text");