How To write an action for a partial view? - asp.net-mvc

string currentUserId = User.Identity.GetUserId();
var us = from u in db.Users
join s in db.Designations
on new { id = u.DesignationID } equals new { id = s.DesignationID }
where u.Id == currentUserId
select new ViewEmployees
{
EmployeeCode = u.UserName,
EmployeeName = u.Name,
Father_Name = u.Father_Name,
DesignationName = s.DesignationName,
EmployeeType = u.EmployeeType,
Email = u.Email,
Mobile = u.Mobile
};
I want to use the output of it as a partial view on another View...
how can i write controller for it..
ActionResult or something Else....?

You can pass your value to partialview first give the path and then pass your model and in partial view bind the related model!
public ActionResult YourMethodName()
{
ViewEmployees us = from u in db.Users
join s in db.Designations
on new { id = u.DesignationID } equals new { id = s.DesignationID }
where u.Id == currentUserId
select new ViewEmployees
{
EmployeeCode = u.UserName,
EmployeeName = u.Name,
Father_Name = u.Father_Name,
DesignationName = s.DesignationName,
EmployeeType = u.EmployeeType,
Email = u.Email,
Mobile = u.Mobile
};
return PartialView("~/PartialViewName", us);
}
and in your partial view
#model eHRManager.Models.ViewEmployees

Related

How To Filter The Data sent To The View According to the user login

This Is My Code
[Authorize(Roles = "Supplier")]
public ActionResult Orders()
{
if (!String.IsNullOrEmpty(TempData["error"] as string))
ViewBag.Error = TempData["error"] as string;
TempData.Clear();
if (User.IsInRole("Admin"))//when the user logs in as the admin
{
var orders = _uow.orderRepo.GetAll().ToList();
List<Models.Admin.OrderGridModel> model = null;
model = (from c in orders
select new Models.Admin.OrderGridModel()
{
OrderNumber = c.OrderNumber,
Date = c.Date,
Id = c.Id,
FullName = c.Person.FirstName + " " + c.Person.LastName,
PhoneNr = c.Person.Tel,
Email = c.Person.Email,
Price = BLL.PriceFormatter.FormatPrice(c.Price, c.Currency),
IsPaid = c.Zaplaceno,
Activities = (from a in c.OrderActivities
select new Models.Admin.OrderGridActivityModel()
{
Id = a.Id,
Time = a.Time,
Name = a.Activity.Name,
Date = a.Date,
Status = a.Status,
Supplier = a.Activity.Supplier != null ? a.Activity.Supplier.Name : "",
BookingRefNr = a.SupplierRefNr,
Hotel = c.Hotelname,
Price = BLL.PriceFormatter.FormatPrice(a.Price, a.Order.Currency),
PriceTypes = BLL.PriceFormatter.GetPriceTypesToString(a.OrderPrices),
voucher_ext = a.VoucherFileExtension,
voucher_name = a.VoucherFileName,
voucher_type = a.VoucherFileContentype,
}).ToList()
}).ToList();
return View(model);
}
if (User.IsInRole("Supplier"))// when the user logs in as the supplier
{
//code for filtering according to the supplier
}
return View();
}
I am getting the orders from the database but i want it to be filtered when the supplier logs in only those records can will be returned in which the supplier name is according to the login
In your repository, you have this
_uow.orderRepo.GetAll();
Create another one where you filter by supplier id
public IList<Order> GetSupplier(string id)
{
return context.Orders.Where(o => o.User.Id = id).ToList();
}
and then you can do this:
_uow.orderRepo.GetSupplier(User.Identity.GetUserId());
Where User.Identity.GetUserId() is the logged in user.

ID value not passed to different action method

In my project, there are two controllers namely Home controller and Hotel controller.I have used view model to combine two model classes.Bellow I have Add my controllers.
Home Controller
public ActionResult Index(){
List<ImageData> details = new List<ImageData>();
var sp_details = (from s in db.service_provider
join p in db.pictures on s.SPID equals p.SPID
join c in db.cities on s.City_ID equals c.City_ID
select new { s.SPID, s.Sp_name, s.Sp_rate, s.service_type, c.Cityname, p.pic }).OrderByDescending(s => s.Sp_rate).Where(p => p.service_type == "Restaurant").Take(3).ToList();
foreach (var item in sp_details)
{
ImageData SpView = new ImageData(); // ViewModel
SpView.SPID = item.SPID;
SpView.Sp_name = item.Sp_name;
SpView.Cityname = item.Cityname;
SpView.Sp_rate = item.Sp_rate;
SpView.pic = item.pic;
details.Add(SpView);
}
return View(details);
}
Hotel controller
public ActionResult Details(int id = 0)
{
List<ImageData> details = new List<ImageData>();
var sp_details = (from s in db.service_provider
join p in db.pictures on s.SPID equals p.SPID
join c in db.cities on s.City_ID equals c.City_ID
where s.SPID == id
select new ImageData()
{
Sp_name = s.Sp_name,
Sp_location = s.Sp_location,
Cityname = c.Cityname,
service_type = s.service_type,
Sp_description = s.Sp_description,
Sp_rate = s.Sp_rate,
Sp_web = s.Sp_web,
Cnt_wh = s.Cnt_wh,
pic = p.pic
});
if (details == null)
{
return HttpNotFound();
}
return View(sp_details);
}
below is part of Index view.I have passed id value to Details action method in Hotel Controller.
<p class="name">#Html.ActionLink(item.Sp_name, "Details","Hotel", new { id = item.SPID })</p>
but value not passed and not display details of Details Action method in Hotel Controller.Since I'm new to mvc 4 I couldn't able to find the mistake.
Try explicitly including an additional null parameter that would represent your htmlAttributes parameter and would match this overload to ensure that your object was properly passed along as route parameters :
#Html.ActionLink(item.Sp_name, "Details","Hotel", new { id = item.SPID }, null)
The ActionLink() helper doesn't contain an overload that only accepts the Text, Action, Controller and RouteValues, which you have supplied, so this extra parameter is necessary.

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.

MVC C# Select Where

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

Resources