MVC C# Select Where - asp.net-mvc

I am trying to add filter by ID for the following:
public ActionResult Index()
{
var model = from o in new MainDBContext().OffLinePayments
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
return View(model);
}
What I would like to do is the following:
public ActionResult Index(long? id)
{
if (id != null)
{
var model = from o in new MainDBContext().OffLinePayments
**Where Assigned_ID == id**
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
return View(model);
}
else
{
var model = from o in new MainDBContext().OffLinePayments
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
return View(model);
}
}

try
var model = from o in new MainDBContext().OffLinePayments
where o.Assigned_ID == id
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};

If I understand correctly, your problem is that the compiler doesn't let you write where o.Assigned_ID == id in the query.
That's because id is a Nullable<long>, which is not implicitly convertible to a long (which OffLinePayment.Assigned_ID presumably is).
You need to write where o.Assigned_ID == id.Value instead. Take a look at what the Value property does so that you don't get any surprises.

A cleaner, shorter and much more readable syntax would look like this:
public ActionResult Index(long? id){
using (var ctx = new MainDBContext())
{
var entities = ctx.OfflinePayments.Where(e => !e.HasValue || e.Assigned_ID == id.Value);
var model = entities.Select(e => new EditOfflinePayment { ID = e.ID, Amount = e.Amount }).ToList();
return View(model);
}
}

Related

How can I throw a sql query into the Viewbag

Hi I have 2 tables in my database. I want to compare and list the news items in table A that are not in table B.
I wrote a sql query.
SELECT ID FROM News_TB
where ID not in ( select News_ID From Slider_TB)
I need a Viewbag that uses this query to do the listing.On account controller.
MY View Code in Account Controller
public ActionResult SliderCategoryDetay(int ID)
{
var kontrol = _udb.SliderCategoryTB_Select().Where(m => m.SliderCategoryID == ID).First();
ViewData["ID"] = kontrol.SliderCategoryID;
ViewBag.slider = _udb.SliderTB_Select().Where(m => m.SliderID == ID);
ViewBag.sliderhabercek = _udb.NewsTB_Select(); /*THİS*/
return View();
}
I want to do it on this page.Thanks for your help.
you can use viewbag.data like this
public ActionResult SliderCategoryDetay(int ID)
{
var kontrol = _udb.SliderCategoryTB_Select().Where(m => m.SliderCategoryID == ID).First();
ViewData["ID"] = kontrol.SliderCategoryID;
ViewBag.data = kontrol;
ViewBag.slider = _udb.SliderTB_Select().Where(m => m.SliderID == ID);
ViewBag.sliderhabercek = _udb.NewsTB_Select(); /*THİS*/
return View();
}
And in your view use following example
#foreach(var item in ViewBag.data)
{
#item.Value
}

Count the No of Element of a column

public ActionResult NoOfLeaves()
{
string CurrentUserID = User.Identity.GetUserId();
var result = (from u in db.LeaveTypes
join s in db.LeaveDetails
on new { id = u.LeaveTypeID } equals new { id = s.LeaveTypeID}
join user in db.Users
on new { id = s.EmpID } equals new { id = user.Id }
where user.Id == CurrentUserID
select new noOfLeavesView
{
EmployeeID = user.Id,
EmployeeName = user.Name,
LeaveTypeName = u.LeaveTypeName,
Issued = u.NoOfLeaves
});
return View(result);
}
Leave type contains the type of Leaves Medical,etc.
Leave Detail contains the History of Leaves Applied by the User.
I want to know how many medical leaves were applied by a user.
public ActionResult NoOfLeaves()
{
var result = (from u in db.LeaveTypes
join s in db.LeaveDetails
on new { id = u.LeaveTypeID } equals new { id = s.LeaveTypeID }
select new noOfLeavesView
{
LeaveTypeName = LeaveTypeId.LeaveTypeName,
Issued = u.NoOfLeaves,
Availed = (db.LeaveDetails.Where(i=>i.LeaveTypeID.Equals(s.LeaveTypeID)).Count()),
}).Distinct();
return View(result);
}
from this way i get the required results...

Some errors in controller (asp.net mvc)

I am getting some errors in my controller.
At first, I got Suppliers List, then I got Id for all Suppliers, then I got all Users for every Supplier.
public ActionResult Grid(bool? active)
{
var suppliers = Context.Suppliers.AsNoTracking()
.WhereIf(active != null, e => e.Active == active)
.Select(e => new SupplierRow
{
Id = e.Id,
FullName = e.FullName,
Active = e.Active,
Visits = e.Visits,
})
.ToList();
List<int> supplierIds = new List<int>();
foreach (SupplierRow sr in suppliers)
{
supplierIds.Add(sr.Id);
}
var users = Context.Users.AsNoTracking()
.Where(e => supplierIds.Contains(e.SupplierId))
.Select(e => new UserRow
{
Id = e.Id,
FullName = e.FullName,
Email = e.Email,
Name = e.Name,
Status = e.Status,
Role = e.Role,
SupplierId = e.SupplierId
}).toList();
foreach (UserRow ur in users)
{
foreach (SupplierRow sr in supplier)
{
if (ur.SupplierId == sr.Id)
{
sr.Users.Add(ur);
}
}
}
return PartialView("_Grid", suppliers);
}
here
and here
What's wrong with my code? How to fix that?
The problem is that you are trying to add Guid object to a collection that only accepts int values. Your User.SupplierId is an object of type Guid? (or Nullable<Guid>), while Supplier.Id is Guid. Fix the collection by declaring it as:
List<Guid> supplierIds = new List<Guid>();
Then in you code use:
foreach(SupplierRow sr in suppliers)
{
supplierIds.Add(sr.Id);
}
Do the same thing for users except that you will have to use SupplierId.HasValue and SupplierId.Value to check whether it has a value and to read the value. This is because it is declared as nullable Guid.

two models in a view - not working for me

I have created an entity data model from my database. however in certain areas of the application i need to pass two models. thus i create a third model which has as properties the objects of each required model.
In the scenario, i want to use one model just to show some data to the user and the other is to be populated by the user using form elements. therefore, i create a constructor in my custom model to populate it. here's the code:
THE CUSTOM MODEL
public class ordersModel
{
public ordersModel(order or)
{
this.prods = new order_products();
this.new_order = new order();
this.new_order.customer_id = or.customer_id;
this.new_order.my_id = or.my_id;
this.new_order.my_order_id = or.my_order_id;
this.new_order.order_date = or.order_date;
this.new_order.order_status_id = or.order_status_id;
}
public order new_order { get; set; }
public order_products prods { get; set; }
}
IT IS USED IN THE CONTROLLER AS FOLLOWS:
public ActionResult Create()
{
order or = new order();
// Store logged-in user's company id in Session
//or.my_id = Session["my_id"].ToString();
//do something to allow user to select customer, maybe use ajax
or.customer_id = "123";
or.order_amount = 0;
or.my_id = "74973f59-1f6c-4f4c-b013-809fa607cad5";
// display date picker to select date
or.order_date = DateTime.Now.Date;
// fetch statuses from database and show in select list box
or.order_status_id = 1;
return View(or);
}
//
// POST: /Orders/Create
[HttpPost]
public ActionResult Create(order or)
{
using (invoicrEntities db = new invoicrEntities())
{
var temp = db.last_order_number.SingleOrDefault(p => p.my_id == or.my_id);
if (temp != null)
{
or.my_order_id = temp.my_order_id + 1;
if (ModelState.IsValid)
{
ordersModel ord = new ordersModel(or);
db.orders.AddObject(or);
temp.my_order_id = temp.my_order_id + 1;
//TempData["my_order_id"] = or.my_order_id;
db.SaveChanges();
return RedirectToAction("AddProducts", ord);
//return RedirectToAction("AddProducts", new { id = or.my_order_id });
}
return View(or);
}
return RedirectToAction("someErrorPageDueToCreateOrder");
}
}
public ActionResult AddProducts()
{
using (invoicrEntities db = new invoicrEntities())
{
//string my_id = TempData["my_id"].ToString();
//string my_order_id = TempData["my_order_id"].ToString();
string my_id = "74973f59-1f6c-4f4c-b013-809fa607cad5";
int my_order_id = 1;
//Int64 my_order_id = Convert.ToInt64(RouteData.Values["order_id"]);
// Display this list in the view
var prods = db.order_products.Where(p => p.my_id == my_id).Where(p => p.my_order_id == my_order_id).ToList();
var or = db.orders.Where(p => p.my_id == my_id).Where(p => p.my_order_id == my_order_id).ToList();
if (or.Count == 1)
{
//ViewData["name"] = "sameer";
ViewData["products_in_list"] = prods;
ViewData["order"] = or[0];
return View();
}
return RedirectToAction("someErrorPageDueToAddProducts");
}
}
[HttpPost]
public ActionResult AddProducts(order_products prod)
{
prod.my_id = "74973f59-1f6c-4f4c-b013-809fa607cad5";
// find a way to get the my_order_id
prod.my_order_id = 1;
return View();
}
THIS ALL WORKS OUT WELL, UNTIL IN THE "ADDPRODUCTS" VIEW:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<invoicr.Models.ordersModel>" %>
AddProducts
<h2>AddProducts</h2>
<%: Model.new_order.my_id %>
the above statement gives an error
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
what am i doing wrong here?
You seem to be passing the wrong model when redisplaying your Create view.
Try passing the ord instance which is of type ordersModel and which is what your view is strongly typed to:
public ActionResult Create(order or)
{
using (invoicrEntities db = new invoicrEntities())
{
var temp = db.last_order_number.SingleOrDefault(p => p.my_id == or.my_id);
if (temp != null)
{
or.my_order_id = temp.my_order_id + 1;
ordersModel ord = new ordersModel(or);
if (ModelState.IsValid)
{
db.orders.AddObject(or);
temp.my_order_id = temp.my_order_id + 1;
db.SaveChanges();
return RedirectToAction("AddProducts", ord);
}
return View(ord);
}
return RedirectToAction("someErrorPageDueToCreateOrder");
}
}
UPDATE:
Now that you have shown your AddProducts action you are not passing any model to the view although your view expects an ordersModel instance. So don't just return View();. You need to pass an instance of ordersModel:
if (or.Count == 1)
{
ViewData["products_in_list"] = prods;
ViewData["order"] = or[0];
ordersModel ord = new ordersModel(or[0]);
return View(ord);
}

Passing and receiving routedictionary values in mvc2

I have a link in my action like this
<%: Html.ActionLink("View Data","Index","MyItem", new {itemId=Model.itemId}, null)%>
now in my newItem controller in its index action how do I retrieve this itemId, so far I have tried
this
public ActionResult Index()
{
RouteData rd = this.RouteData;
var list = from p in rd.DataTokens.Where(p => p.Key == "itemId") select p;
int? id = null;
if (list.Count() > 0)
id = Convert.ToInt32(list.Single().Value);
if (id.HasValue)
{
return View(from a in _Service.List().Where(a => a.ApplicantId == id.Value) select a);
}
else
return View(NORECORDVIEW,);
}
and also this
HttpRequestBase rd = this.Request;
var list = from p in rd.QueryString.AllKeys.Where(p => p. == "itemId") select p;
int? id = null;
if (list.Count() > 0)
id = Convert.ToInt32(list.Single().Value);
if (id.HasValue)
{
return View(from a in Service.List().Where(a => a.ApplicantId == id.Value) select a);
}
else
return View(NORECORDVIEW);
however none of this return the correct value.
In mvc1 we could easily handle that directly but how do you do this in mvc2 please.
You can do this much more easily:
public ActionResult Index(int itemId)
Not only is this 1/10th the code, it's far more easily tested.

Resources