How to pass two queries from in to one view - asp.net-mvc

I want this two methods pass to one view :
public IEnumerable<ProfitAndCostViewModel> getProfitSum()
{
var profBalance = db.Profits
.Where(x => x.IdUser.UserId == WebSecurity.CurrentUserId)
.GroupBy(x => x.IdUser.UserId)
.Select(x => new ProfitAndCostViewModel { ProfitSum = x.Sum(y => y.Value) })
.ToList();
return profBalance;
}
public IEnumerable<ProfitAndCostViewModel> getCostSum()
{
var costBalance = db.Costs
.Where(x => x.IdUser.UserId == WebSecurity.CurrentUserId)
.GroupBy(x => x.IdUser.UserId)
.Select(x => new ProfitAndCostViewModel { CostSum = x.Sum(y => y.Value) })
.ToList();
return costBalance;
}
in my ActionResult I Have this:
var pcv = new ProfitAndCostViewModel();
pcv.ProfModel =getProfitSum();
pcv.CostModel =getCostSum();
return View(pcv);
And in ProfitAndCostViewModel code is this:
public double ProfitSum { get; set; }
public double CostSum { get; set; }
public double FinalBalance { get; set; }
public IEnumerable<ProfitAndCostViewModel> ProfModel { get; set; }
public IEnumerable<ProfitAndCostViewModel> CostModel { get; set; }
this is the error: The model item passed into the dictionary is of type 'WHFM.ViewModels.ProfitAndCostViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[WHFM.ViewModels.ProfitAndCostViewModel]'.`

It looks like your view is strongly typed to IEnumerable<ProfitAndCostViewModel>:
#model IEnumerable<ProfitAndCostViewModel>
but here you are passing a single ProfitAndCostViewModel instance to it:
var pcv = new ProfitAndCostViewModel();
pcv.ProfModel =getProfitSum();
pcv.CostModel =getCostSum();
return View(pcv);
So you should fix the model to which your view is typed:
#model ProfitAndCostViewModel

Related

Foreign key not appearing in View

Can anyone please assist,i have a model that contains a foreign key(ProductCategory).i am trying to call the values of the foreign key but they are not appearing in the view,when i place a breakpoint in the controller all fields appear successful in the raw results view but it seems they are not being passed to the view.
N.B i am using dev express to generate views
public class Product
{
public int Id { get; set; }
public int productCode { get; set; }
public double price { get; set; }
public int ProductCategoryId { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
public Stock itemNo { get; set; }
}
[HttpGet]
public async Task<IActionResult> Get(DataSourceLoadOptions loadOptions) {
var product = _context.Product.Select(i => new {
i.Id,
i.productCode,
i.price,
i.ProductCategoryId,
i.ProductCategory.categoryDescr
});
return Json(await DataSourceLoader.LoadAsync(product, loadOptions));
}
#{
ViewData["Title"] = "Products";
}
<h2 class="content-block">Products</h2>
#(Html.DevExtreme().DataGrid<DevExtremeAspNetCoreApp1.Models.Product>()
.DataSource(ds => ds.Mvc()
.Controller("Products")
.LoadAction("Get")
.InsertAction("Post")
.UpdateAction("Put")
.DeleteAction("Delete")
.Key("Id")
)
.RemoteOperations(true)
.Columns(columns => {
columns.AddFor(m => m.productCode);
columns.AddFor(m => m.price);
columns.AddFor(m => m.ProductCategoryId);
columns.AddFor(m => m.ProductCategory.categoryDescr);
})
.Editing(e => e.Mode(GridEditMode.Popup)
.AllowAdding(true)
.AllowUpdating(true)
.AllowDeleting(true)
.Popup(p=>p
.Title("Product")
.ShowTitle(true)
.Width(500)
.Height(525)
)
)
.Export(e => e.Enabled(true))
)
Try this:
var product = _context.Product.Select(i => new {
i.Id,
i.productCode,
i.price,
i.ProductCategoryId,
ProductCategoryDesc=i.ProductCategory.categoryDescr
});
.....
columns.AddFor(m => m.ProductCategoryDesc);
turns i was passing an anonymous type,correct approach should be:
Controller
public async Task<IActionResult> Get(DataSourceLoadOptions loadOptions) {
var product = _context.Product.Select(i => new {
i.Id,
i.productCode,
i.price,
i.ProductCategoryId,
i.ProductCategory
});
View:
columns.AddFor(m => m.ProductCategory.Id);

Telerik dropdownlist does not seem to bind to JSON

I try to populate the dropdownlist from my database. When loading the view, the dropdownlist spinner appears to do something , then the spinner vanishes and the droplist is empty? Can someone propose a solution. Cheers.
QLine.cs
public partial class QLine
{
[Key]
public int lineId { get; set; }
public int networkId { get; set; }
[Required]
[StringLength(50)]
public string lineName { get; set; }
public virtual QNetwork QNetwork { get; set; }
}
LinesDroplistController.cs
public class LinesDroplistController : Controller
{
private KprModel db = new KprModel();
public JsonResult GetMLines()
{
var result = db.QLines.Where(abc => abc.networkId == 1);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
myView.cshtml
#(Html.Kendo().DropDownList()
.Name("LineDropDownList")
.DataTextField("lineName")
.DataValueField("lineId")
.AutoBind(true)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetMLines", "LinesDroplist");
});
})
)
Please try this:
source.Read(read =>
{
read.Action("GetMLines", "LinesDroplist")
}).ServerFiltering(true);
When the serverFiltering is disabled, then the combobox will not make any additional requests to the server.
It worked when changing
var result = db.QLines.Where(abc => abc.networkId == 1);
to
var result = db.QLines.Where(abc => abc.networkId == 1).Select(x => new { x.lineName, x.lineId });

How can one Fetch respected data from a table using TempData["Id"]

I've This Kendo UI Grid and I'm populating the grid with the values from a couple of tables
I've this GetBrands Method and I can get vales from other tables as you can see in the given method what I can't get is the vale from the TemData["CompanyId"]
how can I get CompanyName from This
public ActionResult GetBrands([DataSourceRequest] DataSourceRequest request)
{
var result= new DataSourceResult();
IQueryable<Brand> brands = null;
try
{
brands = db.Brands;
result = brands.AsQueryable()
.ToList()
.Select(b => new BrandListViewModels()
{
BrandName = b.BrandName,
ProductGroupCode = b.ProductGroupCode !=null? db.ProductGroups.FirstOrDefault(p => p.ProductGroupCode==b.ProductGroupCode).ProductGroupName:"N/A",
ProductSubGroupCode = b.ProductGroupCode != null ? db.ProductSubGroups.FirstOrDefault(p => p.ProductSubGroupCode == b.ProductSubGroupCode).ProductSubGroupName : "N/A",
// CompanyId = Convert.ToInt32(TempData["CompanyId"]) !=null? int.TryParse(db.Companies.FirstOrDefault(c=>c.Id==b.CompanyId).CompanyName, out id):"N/A"
}).OrderBy(b=>b.CompnayName)
.ToDataSourceResult(request);
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
//Temporary storing notification message
TempData["MESSAGE"] = js.Serialize(new { message = "Error has been occured while populating brands", type = "E" });
}
return Json(result,JsonRequestBehavior.AllowGet);
}
I tried To convert It and do lots of other stuff but its not working Its type is Int
Edit
Here is my BrandListViewModel
public class BrandListViewModels
{
public string ProductGroupCode { get; set; }
public string ProductSubGroupCode { get; set; }
public string BrandCode { get; set; }
public string BrandName { get; set; }
public int CompanyId { get; set; }
public string CompnayName { get; set; }
}
Here is my Grid
#(Html.Kendo().Grid(Model)
.Name("BrandGrid")
.Columns(columns =>
{
columns.Bound(c => c.CompanyId).Title("Company");
columns.Bound(c => c.BrandName).Title("Brand");
columns.Bound(c => c.ProductGroupCode).Title("Product Group");
columns.Bound(c => c.ProductSubGroupCode).Title("Product Sub Group");

How to use a View Model to populate a Drop Down list

I'm currently using a ViewBag to pass data to the DropDown list.
I want to use a model instead but I can't get it to work. Here is what I have :
public ActionResult Index(int? catID)
{
GiftListItems viewModel = new GiftListItems
{
Categories = **how do I use this property for DropDown list ?**
};
// using this for DropDown list now :
var query = _categoryRepository.Table
.Select(x => new { x.Id, x.Name })
.Distinct()
.OrderBy(x => x.Name);
ViewBag.Values = new SelectList(query.AsEnumerable(), "Id", "Name");
return View(viewModel);
}
In View :
#Html.DropDownList("catID", (SelectList)ViewBag.Values, new { onchange = "this.form.submit();" })
Model :
public class GiftListItems
{
public IEnumerable<Category> Categories { get; set; }
}
Is this easy to do? Thanks
public class Model
{
public int SelectedItem{get;set;}
public IList<DropDownObj> ListObj{get;set;
public IList<SelectListItem> SelectListItemListObj{get;set;}
{
get
{
var list = (from item in ListObj
select new SelectListItem()
{
Text = item.Id.ToString(CultureInfo.InvariantCulture),
Value item.Name
}).ToList();
return list;
}
set{}
}
}
public class DropDownObj
{
public int Id{get;set;}
public string Name{get;set;
}
usage:
#Html.DropDownListFor(c=>c.SelectedItem,Model.SelectListItemListObj)
Example:
Models:
public class VmSysCategoryModel
{
public int Id { get; set; }
public string Name { get; set; }
}
public class GiftListItemsDropDown
{
public int SelectedCategoryId { get; set; }
public IEnumerable<VmSysCategoryModel> Categories { get; set; }
public IList<SelectListItem> SelectListItemListObj
{
get
{
var list = (from item in Categories
select new SelectListItem()
{
Text = item.Id.ToString(CultureInfo.InvariantCulture),
Value=item.Name
}).ToList();
return list;
}
set { }
}
}
Controller:
public ActionResult Index(int? catID)
{
var listCategories = _categoryRepository.Table
.Select(x => new {x.Id, x.Name})
.Distinct()
.OrderBy(x => x.Name);
var obj = new GiftListItemsDropDown()
{
Categories = Mapper.Map<IList<listCategories>, IList<VmSysCategoryModel>>(listCategories)
//here you mast to map from domain to viewmodel
};
return View(obj);
}
View:
#model GiftListItemsDropDown
#Html.DropDownListFor(c=>c.SelectedCategoryId ,Model.SelectListItemListObj)
You can use the view model like this -
public ActionResult NewsEdit(int ID, dms_New dsn)
{
var query = _categoryRepository.Table
.Select(x => new { x.Id, x.Name })
.Distinct()
.OrderBy(x => x.Name)).ToList();
GiftListItems viewModel = new GiftListItems
{
Categories = query.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.Name
})
};
return View(viewModel);
}
and in your view -
#model GiftListItems
#Html.DropDownList(
"catID",
Model.Categories,
new { onchange = "this.form.submit();" }
)
And your View model now should look like this -
public class GiftListItems
{
public IEnumerable<SelectListItem> Categories { get; set; }
// public IEnumerable<Category> Categories { get; set; } --
}

How to pass two vars from one controller into one view

I want this two methods pass to one view :
public IEnumerable<ProfitAndCostViewModel> getProfitSum()
{
var profBalance = db.Profits
.Where(x => x.IdUser.UserId == WebSecurity.CurrentUserId)
.GroupBy(x => x.IdUser.UserId)
.Select(x => new ProfitAndCostViewModel { ProfitSum = x.Sum(y => y.Value) })
.ToList();
return profBalance;
}
public IEnumerable<ProfitAndCostViewModel> getCostSum()
{
var costBalance = db.Costs
.Where(x => x.IdUser.UserId == WebSecurity.CurrentUserId)
.GroupBy(x => x.IdUser.UserId)
.Select(x => new ProfitAndCostViewModel { CostSum = x.Sum(y => y.Value) })
.ToList();
return costBalance;
}
in my ActionResult I Have this:
ProfitAndCostViewModel pcv = new ProfitAndCostViewModel();
pcv.ProfModel =getProfitSum();
pcv.CostModel =getCostSum();
return View(pcv);
And in ProfitAndCostViewModel code is this:
public double ProfitSum { get; set; }
public double CostSum { get; set; }
public double FinalBalance { get; set; }
public IEnumerable<ProfitAndCostViewModel> ProfModel { get; set; }
public IEnumerable<ProfitAndCostViewModel> CostModel { get; set; }
this is the error:
The model item passed into the dictionary is of type 'WHFM.ViewModels.ProfitAndCostViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[WHFM.ViewModels.ProfitAndCostViewModel]'.
Create a view model which has them both;
public class BigViewModel
{
public List<ProfitsModel> ProfModel { get; set; }
public List<CostsModel> CostModel { get; set; }
}
And controller
public ActionResult Index()
{
BigViewModel model = new BigViewModel();
model.costBalance = db.Costs...;
model.profBalance = db.Profits...;
return View(model)
}
You can wrap your parameters into a ViewModel or use a ViewBag

Resources