exception occurence in mvc - asp.net-mvc

****I am getting an exception of type 'System.IndexOutOfRangeException' in System.Data.dll but was not handled in user code****
public List<ItemModel> med()
{
List<ItemModel> itemList = new List<ItemModel>();
connection();
SqlCommand cmd = new SqlCommand("procmedication_dropdown1", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PstrOperationFlag", "S-drugname");
con.Open();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
ItemModel item = new ItemModel();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
ItemModel io = new ItemModel();
while (sdr.Read())
{
io = new ItemModel();
io.medication = sdr["medications"].ToString();
itemList.Add(io);
}
}
con.Close();
return itemList;
}
}
}

Try this
public List<ItemModel> med()
{
List<ItemModel> itemList = new List<ItemModel>();
ItemModel io;
connection();
SqlCommand cmd = new SqlCommand("procmedication_dropdown1", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PstrOperationFlag", "S-drugname");
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
io = new ItemModel();
io.medication = sdr["medications"].ToString();
itemList.Add(io);
}
}
con.Close();
return itemList;
}

Related

Hi I'm trying to import the captured excel file into table on a button click

enter image description here
Hi I want to export the sheets of excel into a table. I already manage to catch the excel into database. When I click the import button I want to redirect it into a new view and see there the excel values. Any idea how I can do that? I'm using MVC
here is my controller:
public ActionResult Index()
{
Products products = GetProducts();
ViewBag.Message = "";
return View(products);
}
}
[HttpPost]
public ActionResult Index(Products obj)
{
string strDateTime = System.DateTime.Now.ToString("ddMMyyyyHHMMss");
string finalPath = "\\UploadedFile\\" + strDateTime + obj.UploadFile.FileName;
obj.UploadFile.SaveAs(Server.MapPath("~") + finalPath);
obj.FilePath = strDateTime + obj.UploadFile.FileName;
ViewBag.Message = SaveToDB(obj);
Products products = GetProducts();
return View(products);
}
public string SaveToDB(Products obj)
{
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "sp_AddFiles";
cmd.Parameters.AddWithValue("#FileN", obj.FileN);
cmd.Parameters.AddWithValue("#FilePath", obj.FilePath);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Dispose();
con.Close();
return "Saved Successfully";
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
// GET: Products
public Products GetProducts()
{
Products products = new Products();
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand("Select * from tblFiles", con);
con.Open();
adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
adapter.Dispose();
cmd.Dispose();
con.Close();
products.lstProducts = new List<Products>();
foreach (DataRow dr in dt.Rows)
{
products.lstProducts.Add(new Products
{
FileN = dr["FileN"].ToString(),
FilePath = dr["FilePath"].ToString()
});
}
}
catch (Exception ex)
{
adapter.Dispose();
cmd.Dispose();
con.Close();
}
if (products == null || products.lstProducts == null || products.lstProducts.Count == 0)
{
products = new Products();
products.lstProducts = new List<Products>();
}
return products;
}
Hi I want to export the sheets of excel into a table. I already manage to catch the excel into database. When I click the import button I want to redirect it into a new view and see there the excel values. Any idea how I can do that? I'm using MVC

Crud operation in asp.net mvc

I have an assignment in ASP.NET MVC and I try to write a crud operation without Entity Framework, but the code is not working correctly.
This is my code:
List<bookModel> books = new List<bookModel>();
SqlConnection con = new SqlConnection("Data Source=DESKTOP-VKO8311;Initial Catalog=BookStore;Integrated Security=True");
string query = "SELECT * FROM books";
SqlCommand command = new SqlCommand(query, con);
try
{
con.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
books.Add(new bookModel
{
Title = reader["Title of book"].ToString(),
Author = reader["Author"].ToString(),
Price = reader["Price"].ToString()
});
con.Close();
}
}
catch (Exception ex)
{
con.Close();
}
return View(books);
[HttpGet]
public ActionResult NewBook()
{
ViewBag.Title = "Add New Book";
return View();
}
[HttpPost]
public ActionResult NewBook(bookModel model)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-VKO8311;Initial Catalog=BookStore;Integrated Security=True");
string query = "insert into books values(#Ti, #au, #pr)";
SqlCommand command = new SqlCommand(query, con);
command.Parameters.Add("#Ti", System.Data.SqlDbType.VarChar);
command.Parameters["#Ti"].Value = model.Title;
command.Parameters.Add("#au", System.Data.SqlDbType.VarChar);
command.Parameters["#au"].Value = model.author;
command.Parameters.Add("#pr", System.Data.SqlDbType.VarChar);
command.Parameters["#pr"].Value = model.Price;
try
{
con.Open();
command.ExecuteNonQuery();
MessageBox.Show("insert was successful");
return RedirectToAction("books");
}
catch (Exception ex)
{
con.Close();
}
return View();
}
The books.cshtml does not show the result from the database and also the newbook.cshtml does not redirect the create result in the database also.
Any help please?
Your code needs refactoring, but the biggest issue is where you are closing your connection. You don't do it while you're iterating the data reader. Also, take the connection close out of your exception handler. You're better off enclosing it in a using block.
while (reader.Read())
{
books.Add(new bookModel
{
Title = reader["Title of book"].ToString(),
Author = reader["Author"].ToString(),
Price = reader["Price"].ToString()
});
}

How to check if a checkbox was checked in mvc controller

I'm pulling a list of items from table database and checkbox to check and approve each item; however even when I check the item it throws this error message : Please select at least one requested item. What I'm trying to achieve is that the user checks any amount of items in the list and then the status requisition number is updated to 0.
public ActionResult RequisitionList(List<Requisition> postingObj)
{
IssueDAO dbObj = new DAO(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
List<string> reqNumbers = new List<string>();
bool check=false;
foreach (var item in postingObj)
{
if (item.postTrnx)
{
reqNumbers.Add(item.reqNumber);
}
}
if (check == true)
{
dbObj.SetRequisitionStatus0(reqNumbers);
ViewBag.Message = "Approval Successful!";
}
else {
ViewBag.Message = "Please select at least one requested item";
return View(dbObj.GetAllRequest());
}
return View(dbObj.GetAllRequest());
}
public void SetRequisitionStatus0(List<string> reqNumbers)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandText = "requisition_sp_setstatus0";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#reqNumber", SqlDbType.VarChar);
command.Parameters.Add("#approve_date", SqlDbType.DateTime).Value = DateTime.Now;
using (command.Connection = connection)
{
try
{
connection.Open();
foreach (var item in reqNumbers)
{
command.Parameters["#reqNumber"].Value = item;
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
}
return;
}
public List<Requisition> GetAllRequest()
{
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("getallrequests", connection))
{
command.CommandType = CommandType.StoredProcedure;
List<Requisition> request = new List<Requisition>();
SqlDataReader rdrObj;
connection.Open();
rdrObj = command.ExecuteReader();
while (rdrObj.Read())
{
Requisition requisition = new Requisition();
requisition.reqNumber = rdrObj.GetString(0);
requisition.reqDate = rdrObj.GetDateTime(1);
requisition.items = getRequestItemByRquisition(rdrObj.GetString(0));
request.Add(requisition);
}
rdrObj.Close();
return request;
}
}
}

I am getting an error at get property with error 'BusinessLayer.EmployeeBusinessLayer.Employees.get': not all code paths return a value

I am getting an error at get property that not all code paths return a value.
namespace BusinessLayer
{
class EmployeeBusinessLayer
{
public IEnumerable<Employee> Employees
{
get // Here i am getting an error that not all code paths return a value
{
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
List<Employee> employees = new List<Employee>();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("spGetEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
employee.Emp_Name = Convert.ToString(rdr["Emp_Name"]);
employee.Designation = Convert.ToString(rdr["Designation"]);
employee.City = Convert.ToString(rdr["City"]);
employee.State = Convert.ToString(rdr["State"]);
employee.Country = Convert.ToString(rdr["Country"]);
employees.Add(employee);
}
}
}
}
}
}
The error message can be taken literally:
namespace BusinessLayer
{
class EmployeeBusinessLayer
{
public IEnumerable<Employee> Employees
{
get // Here i am getting an error that not all code paths return a value
{
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
List<Employee> employees = new List<Employee>();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("spGetEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
employee.Emp_Name = Convert.ToString(rdr["Emp_Name"]);
employee.Designation = Convert.ToString(rdr["Designation"]);
employee.City = Convert.ToString(rdr["City"]);
employee.State = Convert.ToString(rdr["State"]);
employee.Country = Convert.ToString(rdr["Country"]);
employees.Add(employee);
}
}
return employees;
}
}
}
}
Need to return your employees. Also you should Close() and dispose your reader.
using(IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Employee employee = new Employee();
employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
...
employees.Add(employee);
}
rdr.Close();
}
return employees;

How to fill dropdownlist in MVC-4 using dapper

I filled Drop Down List in MVC which is working fine but now I want to do it using Dapper but got stuck.
DropDownList in MVC without Dapper
Controller
[HttpPost]
public ActionResult Create(User ur)
{
string str = #"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
SqlConnection con = new SqlConnection(str);
string query = "Insert into tblTest (Name,Email,MobileNo) values('" + ur.Name + "','" + ur.Email + "','" + ur.MobileNo + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
TempData["msg"] = "<script>alert('Inserted Successfully');</script>";
ModelState.Clear();
FillCountry();
}
public void FillCountry()
{
string str = #"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
SqlConnection con = new SqlConnection(str);
string query = "select * from tbl_country ";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select", Value = "0" });
while (rdr.Read())
{
li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
}
ViewData["country"] = li;
}
View
#{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
#Html.DropDownList("country", ViewData["country"] as List<SelectListItem>, new {onchange = "this.form.submit();" })
#{ Html.EndForm(); }
This is what I am trying to do now
DropDownList in MVC with Dapper
Model
public class Region
{
private int _CountryId;
private string _CountryName;
public int CountryId
{
get { return _CountryId; }
set { _CountryId = value; }
}
public string CountryName
{
get { return _CountryName; }
set { _CountryName = value; }
}
Controller
[HttpPost]
public ActionResult AddMobiles(TBMobileDetails MD, HttpPostedFileBase file)
{
FileUpload(file);
MobileMain MM = new MobileMain();
MM.AddMobiles(MD);
FillCountry();
return RedirectToAction("AllMobileList");
}
Stuck in this part how to fill it using dapper? How to populate my list?
public void FillCountry()
{
List<Region> li = new List<Region>();
var para = new DynamicParameters();
para.Add("#Type", 1);
var result = con.Query<Region>("Sp_MVCDapperDDl", para, commandType: CommandType.StoredProcedure);
}
View
#{ Html.BeginForm("AddMobiles", "AddMobile", FormMethod.Post, new { enctype = "multipart/form-data" }); }
#Html.DropDownList("country", ViewData["country"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
#{ Html.EndForm(); }
You are passing in ViewData["country"] object of type IEnumerable<Region> while in View you are casting it to IEnumerable<SelectListItem> which won't work obviously in action change FillCountry() to make SelectList:
public void FillCountry()
{
List<Region> li = new List<Region>();
var para = new DynamicParameters();
para.Add("#Type", 1);
var result = con.Query<Region>("Sp_MVCDapperDDl", para, commandType: CommandType.StoredProcedure);
var list = new SelectList(result,"CountryId","CountryName");
}
and in View now cast it to SelectList:
#Html.DropDownList("country", ViewData["country"] as SelectList, new {onchange = "this.form.submit();" })
This will get you going.

Resources