How to Populate DropDownList from the Database in MVC - asp.net-mvc

I am new to ASP NET MVC
I need Populate a drop down list from values obtained from a database table using MySql database and view model, after checking if the current user is application enabled, using ASP NET MVC.
This is the tutorial
My code below return
Error: returns void, a return keyword must not be followed by an object expression
On this line
return items;
Any help really appreciated.
Controller
public ActionResult Recovery()
{
try
{
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (var connection =
new MySqlConnection(cs))
{
string commandText = " SELECT cCountry FROM `dotable_user` " +
" WHERE cName = #Username; ";
using (var command =
new MySqlCommand(commandText, connection))
{
if (!String.IsNullOrEmpty(HttpContext.User.Identity.Name.ToString()))
{
command.Parameters.AddWithValue("#Username", HttpContext.User.Identity.Name.ToString());
}
connection.Open();
string cCountry = (string)command.ExecuteScalar();
if (String.IsNullOrEmpty(cCountry))
{
TempData["Message"] = "No user.";
ViewBag.Message = String.Format("No user.");
}
List<SelectListItem> items = new List<SelectListItem>();
using (MySqlConnection con = new MySqlConnection(cs))
{
string query = " SELECT cCountry FROM `dotable_countries` " +
" WHERE cCountry = '" + cCountry.ToString() + "' ";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["cCountry"].ToString(),
Value = sdr["cCountry"].ToString()
});
}
}
connection.Close();
}
}
return items;
}
}
}
catch (Exception ex)
{
TempData["Message"] = "Login failed.Error - " + ex.Message;
}
}
Update
I have tried with this code.
I have error
Error CS0103 The name 'cCountry' does not exist in the current context
public ActionResult Recovery()
{
try
{
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (var connection =
new MySqlConnection(cs))
{
string commandText = " SELECT cCountry FROM `dotable_user` " +
" WHERE cName = #Username; ";
using (var command =
new MySqlCommand(commandText, connection))
{
if (!String.IsNullOrEmpty(HttpContext.User.Identity.Name.ToString()))
{
command.Parameters.AddWithValue("#Username", HttpContext.User.Identity.Name.ToString());
}
connection.Open();
string cCountry = (string)command.ExecuteScalar();
if (String.IsNullOrEmpty(cCountry))
{
TempData["Message"] = "No user.";
ViewBag.Message = String.Format("No user.");
}
TempData["Dates"] = PopulateDates();
}
}
}
catch (Exception ex)
{
TempData["Message"] = "Login failed.Error - " + ex.Message;
}
}
private static List<SelectListItem> PopulateDates()
{
List<SelectListItem> items = new List<SelectListItem>();
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
string query = " SELECT cCountry FROM `dotable_countries` " +
" WHERE cCountry = '" + cCountry.ToString() + "'; ";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["cCountry"].ToString(),
Value = sdr["cCountry"].ToString()
});
}
}
cmd.Connection.Close();
}
}
return items;
}

You are not passing cCountry value to populateDates.That's why you are getting this error. You can do something like below to get drop down populated. However it is not good idea to write Business Logic directly in controller. You should move it to model or Business layer.
private static List<SelectListItem> PopulateDates(string country)
{
List<SelectListItem> items = new List<SelectListItem>();
string cs = ConfigurationManager.ConnectionStrings["cnj"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
string query = " SELECT cCountry FROM dotable_countries WHERE cCountry = #country";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Parameters.AddWithValue("#country",country);
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["cCountry"].ToString(),
Value = sdr["cCountry"].ToString()
});
}
}
cmd.Connection.Close();
}
}
return items;
}
and while calling this method in Action pass country value to it like below
TempData["Dates"] = PopulateDates(cCountry);

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

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.

Attachment is not attached to the email asp.net mvc

I have two forms on my mvc site, FeedbackForm and CareerForm. I need to send both forms to the same email. I created two models for my forms and two views, then I added in the first my controller
/*Feedback*/
[HttpGet]
public ActionResult Feedback(string ErrorMessage)
{
if (ErrorMessage != null)
{
}
return View();
}
[HttpPost]
public ActionResult Feedback(FeedbackForm Model)
{
string ErrorMessage;
//email
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.BodyEncoding = Encoding.UTF8;
msg.Priority = MailPriority.High;
msg.From = new MailAddress(Model.Email, Model.Name);
msg.To.Add("tayna-anita#mail.ru");
msg.Subject = #Resources.Global.Feedback_Email_Title + " " + Model.Company;
string message = #Resources.Global.Feedback_Email_From + " " + Model.Name + "\n"
+ #Resources.Global.Feedback_Email + " " + Model.Email + "\n"
+ #Resources.Global.Feedback_Phone + " " + Model.Phone + "\n"
+ #Resources.Global.Feedback_Company + " " + Model.Company + "\n\n"
+ Model.AdditionalInformation;
msg.Body = message;
msg.IsBodyHtml = false;
//Attachment
if (Model.ProjectInformation != null && !(String.IsNullOrEmpty(Model.ProjectInformation.FileName)))
{
HttpPostedFileBase attFile = Model.ProjectInformation;
if (attFile.ContentLength > 0)
{
var attach = new Attachment(attFile.InputStream, attFile.FileName);
msg.Attachments.Add(attach);
}
}
SmtpClient client = new SmtpClient("denver.corepartners.local", 55);
client.UseDefaultCredentials = false;
client.EnableSsl = false;
try
{
client.Send(msg);
}
catch (Exception ex)
{
return RedirectToAction("Feedback", "Home", ErrorMessage = "Ошибка при отправке письма, попробуйте позже");
}
return RedirectToAction("Feedback", "Home");
}
and added to the second controller
/*CareerForm*/
[HttpGet]
public ActionResult CareerForm()
{
CareerForm model = new CareerForm();
model.StartNow = true;
model.EmploymentType = new List<CheckBoxes>
{
new CheckBoxes { Text = "полная занятость" },
new CheckBoxes { Text = "частичная занятость" },
new CheckBoxes { Text = "контракт" }
};
return View(model);
}
[HttpPost]
public ActionResult CareerForm(CareerForm Model)
{
string ErrorMessage;
//curricula vitae to email
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.BodyEncoding = Encoding.UTF8;
msg.Priority = MailPriority.Normal;
msg.From = new MailAddress(Model.Email, Model.Name + " " + Model.Surname);
msg.To.Add("tayna-anita#mail.ru");
msg.Subject = "Анкета с сайта";
string message = "Имя: " + Model.Name + " " + Model.Surname + "\n"
+ "Контактный телефон: " + Model.Phone + "\n";
if (Model.Adress != null)
{
message += "Адрес: " + Model.Adress + "\n";
}
message += "Email: " + Model.Email + "\n"
+ "Желаемая должность: " + Model.Position;
bool check = false;
foreach (var item in Model.EmploymentType)
{
if (item.Checked) check = true;
};
if (check == true)
{
message += "\nТип занятости: ";
foreach (var item in Model.EmploymentType)
{
if (item.Checked) message += item.Text + " ";
};
}
else
{
message += "\nТип занятости: не выбран";
}
if (Model.StartNow)
{
message += "\nМогу ли немедленно приступить к работе: да";
}
else
{
message += "\nГотов приступить к работе с: " + Model.StartFrom;
}
msg.Body = message;
msg.IsBodyHtml = false;
//Attachment
if (Model.Resume != null && !(String.IsNullOrEmpty(Model.Resume.FileName)))
{
HttpPostedFileBase attFile = Model.Resume;
if (attFile.ContentLength > 0)
{
var attach = new Attachment(attFile.InputStream, attFile.FileName);
msg.Attachments.Add(attach);
}
}
SmtpClient client = new SmtpClient("denver.corepartners.local", 55);
client.UseDefaultCredentials = false;
client.EnableSsl = false;
try
{
client.Send(msg);
}
catch (Exception ex)
{
return RedirectToAction("CareerForm", "Career", ErrorMessage = "Ошибка при отправке письма, попробуйте позже");
}
return RedirectToAction("CareerForm", "Career");
}
But I get an attached file only at the first case, when I send FeedbackForm to email.
For CareerForm I get email, but every time it is without an attachment.
I checked in debagger and I saw Model.Resume = null every time, but I dont undestand why.
what's wrong with my code?
Maybe it's bacause I create CareerForm model = new CareerForm(); in [HttpGet] ?
How can I fix that?
UPD
Views:
FeedbackForm http://jsfiddle.net/fcnk9/
CareerForm http://jsfiddle.net/9Gz9u/
You need to set enctype = "multipart/form-data" in your Career form, just like you have in your Feedback form...
#using (Html.BeginForm("CareerForm", "Career", FormMethod.Post, new { id = "career-form", #class = "form-horizontal", enctype = "multipart/form-data" }))
For more information as to why, see Why File Upload didn't work without enctype?

Resources