Get multiple nested partial views in MVC - asp.net-mvc

I have one page which contains one multiple partial pages. In each partial view there will be again multiple partial pages. When I am getting this, it will add data table to ds contains three tables. How can I show it in hierarchical order?
In my ds three tables come from DB shows particular record. How can I display this?
THis is my DAL:
public static ConsignmentNote GetConsignmentNoteByID(int id)
{
ConsignmentNote consignmentnote = null;
SqlConnection sqlConnection = null;
sqlConnection = SqlConnectionHelper.GetConnectionConnectionString();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
try
{
cmd = new SqlCommand("GetConsignmentNoteByCNNoteId", sqlConnection);
cmd.Parameters.Add(new SqlParameter("#ConsignmentNoteID", id));
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(ds);
//First table data
if (ds.Tables[0].Rows.Count > 0)
{
DataRow row = ds.Tables[0].Rows[0];
consignmentnote = new ConsignmentNote(row);
}
else
{
consignmentnote = new ConsignmentNote();
}
//Second table data
consignmentnote.LstAdditionalCN = new List<AdditionalCN>();
int rowIndexCN = 1;
if (ds.Tables[1].Rows.Count > 0)
{
int i = 0;
foreach (DataRow acnRow in ds.Tables[i].Rows)
{
AdditionalCN objACN = new AdditionalCN();
objACN.ConsignmentNoteRelID = acnRow["ConsignmentNoteRelID"] as Int32? ?? 0;
objACN.ConsignmentNoteID = acnRow["ConsignmentNoteID"] as Int32? ?? 0;
objACN.ConsignmentNoteNumber = acnRow["ConsignmentNoteNumber"] as string ?? null;
objACN.CNDate = acnRow["CNDate"] as DateTime? ?? DateTime.MinValue;
objACN.ConsignerID = (acnRow["ConsignerID"] as Int32? ?? 0).ToString();
objACN.ConsigneeID = (acnRow["ConsigneeID"] as Int32? ?? 0).ToString();
objACN.LocationFrom = acnRow["LocationFrom"] as string ?? null;
objACN.LocationTo = acnRow["LocationTo"] as string ?? null;
if (rowIndexCN == 1)
{
//insert to default CNI
consignmentnote.ConsignmentNoteRelID = objACN.ConsignmentNoteRelID;
consignmentnote.ConsignmentNoteNumber = objACN.ConsignmentNoteNumber;
}
else
{
//insert to additional CNI
consignmentnote.LstAdditionalCN.Add(objACN);
}
rowIndexCN++;
}
}
consignmentnote.LstAdditionalInvoice = new List<AdditionalInvoice>();
int rowIndexCNInvoice = 1;
if (ds.Tables[2].Rows.Count > 0)
{
foreach (DataRow acnRow in ds.Tables[2].Rows)
{
AdditionalInvoice objACN = new AdditionalInvoice();
objACN.ConsignmentNoteLineItemID = acnRow["ConsignmentNoteLineItemID"] as Int32? ?? 0;
objACN.ConsignmentNoteID = acnRow["ConsignmentNoteID"] as Int32? ?? 0;
objACN.ConsignmentNoteRelID = acnRow["ConsignmentNoteRelID"] as Int32? ?? 0;
objACN.ProjectPO = (acnRow["ProjectPO"] as Int32? ?? 0).ToString();
objACN.InvoiceNum = (acnRow["InvoiceNum"] as Int32? ?? 0).ToString();
objACN.InvoiceDate = acnRow["InvoiceDate"] as DateTime? ?? DateTime.MinValue;
objACN.Pkgs = acnRow["Pkgs"] as string ?? null;
objACN.Description = acnRow["Description"] as string ?? null;
objACN.ActualWeight = acnRow["ActualWeight"] as string ?? null;
objACN.ChargedWeight = acnRow["ChargedWeight"] as string ?? null;
objACN.InvoiceValue = acnRow["InvoiceValue"] as decimal? ?? 0;
if (rowIndexCNInvoice == 1)
{
//insert to default CNI
consignmentnote.ConsignmentNoteRelID = objACN.ConsignmentNoteRelID;
consignmentnote.ConsignmentNoteID = objACN.ConsignmentNoteID;
}
else
{
//insert to additional CNI
consignmentnote.LstAdditionalInvoice.Add(objACN);
}
rowIndexCNInvoice++;
}
}
}
catch (Exception x)
{
throw x;
}
finally
{
}
return consignmentnote;
}

Related

How to Populate DropDownList from the Database in 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);

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;
}
}
}

Using the generic type 'PagedList.StaticPagedList<T>' requires 1 type arguments

I am working on user roles using Asp.net MVC. I am stuck while working on Admin section. I have mentioned one question above and the second question is similar which is Using the generic type 'System.Collections.Generic.List' requires 1 type arguments
Here is my code.
public ActionResult Index(string searchStringUserNameOrEmail, string currentFilter, int? page)
{
try
{
int intPage = 1;
int intPageSize = 5;
int intTotalPageCount = 0;
if (searchStringUserNameOrEmail != null)
{
intPage = 1;
}
else
{
if (currentFilter != null)
{
searchStringUserNameOrEmail = currentFilter;
intPage = page ?? 1;
}
else
{
searchStringUserNameOrEmail = "";
intPage = page ?? 1;
}
}
ViewBag.CurrentFilter = searchStringUserNameOrEmail;
List col_UserDTO = new List();
int intSkip = (intPage - 1) * intPageSize;
intTotalPageCount = UserManager.Users
.Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
.Count();
var result = UserManager.Users
.Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
.OrderBy(x => x.UserName)
.Skip(intSkip)
.Take(intPageSize)
.ToList();
foreach (var item in result)
{
ExpandedUserDTO objUserDTO = new ExpandedUserDTO();
objUserDTO.UserName = item.UserName;
objUserDTO.Email = item.Email;
objUserDTO.LockoutEndDateUtc = item.LockoutEndDateUtc;
col_UserDTO.Add(objUserDTO);
}
// Set the number of pages
// Error appears here
var _UserDTOAsIPagedList =
new StaticPagedList
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
return View(_UserDTOAsIPagedList);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error: " + ex);
List col_UserDTO = new List(); // Error appears here
return View(col_UserDTO.ToPagedList(1, 25));
}
}
#endregion
`
StaticPagedList is generic. You need to supply the type of collection(for col_UserDTO), in your case List:
var _UserDTOAsIPagedList =
new StaticPagedList<List<ExpandedUserDTO>>
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
See http://www.programering.com/a/MTN2gDNwATM.html
You may need to change List col_UserDTO references to List<ExpandedUserDTO> col_UserDTO
Use this instead
var _UserDTOAsIPagedList =
new StaticPagedList<ExpandedUserDTO>
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);

Pass object to another action of ASP.net MVC 2

I have one view that used to display the result of my search item. This is its controller :
[HttpPost]
public ActionResult EvaluatingReport(FormCollection frm)
{
string empType = frm["empType"].ToString();
int totalMonth = 3;
int mon = DateTime.Now.Month;
int yr = DateTime.Now.Year;
string Curdate = mon + "/" + yr;
DateTime date = new DateTime();
var result = (from e in context.tblEmployees
join p in context.tblEmployee_Position on e.PositionIDF equals p.PositionID
select new EvaluateEmployee
{
ID = e.Code,
IDCard = e.IDCard,
Name = e.NameEng,
DOB = e.DOB,
Position = p.Position,
Sex = e.Sex,
StartDate = e.StartDate
}).ToList();
result = result.Where(((s => mon - int.Parse(s.StartDate.Substring(3, 2).ToString()) == totalMonth && yr -int.Parse(s.StartDate.Substring(6, 4).ToString()) == totalYear))).ToList();
ViewData["EmployeeType"] = result;
return View();
}
I displayed the content in the view by looping ViewData["EmployeeType"] and I also included one Print label :
<script language="javascript" type="text/javascript">
function printChart() {
var URL = "EvaluatingReport";
var W = window.open(URL);
W.window.print();
}
function printPage(sURL) {
var oHiddFrame = document.createElement("iframe");
oHiddFrame.src = sURL;
oHiddFrame.style.visibility = "hidden";
oHiddFrame.style.position = "fixed";
oHiddFrame.style.right = "0";
oHiddFrame.style.bottom = "0";
document.body.appendChild(oHiddFrame);
oHiddFrame.contentWindow.onload = oHiddFrame.contentWindow.print;
oHiddFrame.contentWindow.onafterprint = function () {
document.body.removeChild(oHiddFrame); };
}
</script>
<span onclick="printPage('/Report/PrintEvaluatingReport');" style="cursor:pointer;text-decoration:none;color:#0000ff;">
<img src="../../Content/images/Print.png" width="35px;" alt="print" style="position:relative;top:6px;"/>
Print Report
</span>
I used function printPage('/Report/PrintEvaluatingReport') to load the print dialog with the action PrintEvaluatingReport. So I want to take the object that I have in EvaluatingReport to the action PrintEvaluatingReport.
Could anyone tell me how could I do that?
Thanks in advanced.
You could use TempData["EmployeeType"]
[HttpPost]
public ActionResult EvaluatingReport(FormCollection frm)
{
string empType = frm["empType"].ToString();
int totalMonth = 3;
int mon = DateTime.Now.Month;
int yr = DateTime.Now.Year;
string Curdate = mon + "/" + yr;
DateTime date = new DateTime();
var result = (from e in context.tblEmployees
join p in context.tblEmployee_Position on e.PositionIDF equals p.PositionID
select new EvaluateEmployee
{
ID = e.Code,
IDCard = e.IDCard,
Name = e.NameEng,
DOB = e.DOB,
Position = p.Position,
Sex = e.Sex,
StartDate = e.StartDate
}).ToList();
result = result.Where(((s => mon - int.Parse(s.StartDate.Substring(3, 2).ToString()) == totalMonth && yr -int.Parse(s.StartDate.Substring(6, 4).ToString()) == totalYear))).ToList();
ViewData["EmployeeType"] = result;
// Store in TempData to be read by PrintEvaluatingReport
TempData["EmployeeType"] = result;
return View();
}
public ActionResult PrintEvaluatingReport()
{
var employeeType = TempData["EmployeeType"] as EmployeeType;
// do stuff
return View();
}
You can use a session variable for that !!
private EmployeeType Result
{
get { return (EmployeeType)this.Session["Result"]; }
set
{
this.Session["Result"] = value;
}
}
[HttpPost]
public ActionResult EvaluatingReport(FormCollection frm)
{
.
.
.
// Store in Session
this.Result = result;
return View();
}
public ActionResult PrintEvaluatingReport()
{
var employeeType = this.Result;
.
.
.
}

Blackberry - get contacts list

I wanted to get the list of all names and their corresponding email address from the contact list in blackberry JDE 4.7 can anyone help with the code for getting the above mentioned things..
Thanks in advance...
try this code:
public Scr() {
Vector v = getContacts();
Enumeration iterator = v.elements();
while (iterator.hasMoreElements()) {
String[] contact = (String[]) iterator.nextElement();
for (int i = 0; i < contact.length; i++)
add(new LabelField(contact[i]));
}
}
private Vector getContacts() {
Vector result = new Vector();
try {
BlackBerryContactList contactList = (BlackBerryContactList) PIM
.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
Enumeration enumx = contactList.items();
while (enumx.hasMoreElements()) {
BlackBerryContact c = (BlackBerryContact) enumx.nextElement();
String[] contact = new String[2];
if (contactList.isSupportedField(BlackBerryContact.NAME)) {
String[] name = c.getStringArray(BlackBerryContact.NAME, 0);
String firstName = name[Contact.NAME_GIVEN];
String lastName = name[Contact.NAME_FAMILY];
contact[0] = firstName + " " + lastName;
}
if (contactList.isSupportedField(BlackBerryContact.EMAIL)) {
StringBuffer emails = new StringBuffer();
int emailCount = c.countValues(BlackBerryContact.EMAIL);
for (int i = 0; i < emailCount; i++) {
String email = c.getString(BlackBerryContact.EMAIL, i);
if (email != null) {
emails.append(email.trim());
emails.append("; ");
}
}
contact[1] = emails.toString();
}
result.addElement(contact);
}
} catch (PIMException ex) {
ex.printStackTrace();
}
return result;
}

Resources