I am trying to add many json lists to another json object to send to the view, however I am not sure how to add all of them to a single object as it is not always certain how many lists there will be.
Here is what I have so far in my controller, I get each list from a LINQ query from my model and convert it to a list that is stored in a var.
/////////////////////////////////////////////
//Actions for Export //
///////////////////////////////////////////
public JsonResult GetInfoToExport()
{
using (InsertModelEntities dc = new InsertModelEntities())
{
CleintEntities cleints = new CleintEntities();
var ClientList = cleints.Clients.ToList();
var JsonToSend = new JsonResult();
foreach (var Company in ClientList)
{
var ClientInfo = (from E in dc.EventsAllLocations
join C in cleints.Clients on E.CompanyName equals C.Company
where C.Company == Company.ToString() && E.Start.Year == DateTime.Now.Year && E.Start.Month == DateTime.Now.Month
select new
{
Company = E.CompanyName,
Location = E.Location,
HoursPaid = C.HoursPayed,
Start = E.Start,
End = E.End,
Time = E.End - E.Start
}).ToList();
JsonToSend.
//Not sure how to add each of these ClientInfo list items to the JsonToSend object
}
return new JsonResult { Data = JsonToSend, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
I want to be able to add each ClientInfo list to the JsonToSend Object and just send that, but looking online I cant find any syntax on how to do this. Any help or nudge in the right direction will be much appreciated!
Thanks in advance! :)
Edit:
Also tried:
List<JsonResult> bookings = new List<JsonResult>();
// var JsonToSend = new JsonResult();
foreach (var Company in ClientList)
{
var ClientInfo = (from E in dc.EventsAllLocations
join C in cleints.Clients on E.CompanyName equals C.Company
where C.Company == Company.ToString() && E.Start.Year == DateTime.Now.Year && E.Start.Month == DateTime.Now.Month
select new
{
Company = E.CompanyName,
Location = E.Location,
HoursPaid = C.HoursPayed,
Start = E.Start,
End = E.End,
Time = E.End - E.Start
}).ToList();
bookings.Add(ClientInfo);
//Not sure how to add each of these ClientInfo list items to the JsonToSend object
}
and getting the error
"Cannot convert from generic list to syste.web.mvc.JsonResult"
I usually convert the data into a List<> before returning it to the View, like below.
public JsonResult GetInfoToExport()
{
CleintEntities cleints = new CleintEntities();
var ClientList = cleints.Clients.ToList();
List<object> ReturnData = new List<object>();
foreach (var Company in ClientList)
{
ReturnData.Add(new { CompanyName = Company.Name, ID = Company.ID //
etc });
}
return Json(new { Data = ReturnData }, JsonRequestBehavior.AllowGet);
}
You can then access the JSON object data on the view like such:
<script type="text/javascript">
function GetClientData()
{
$.ajax({
url: '/Controller/GetInfoToExport,
dataType: 'json',
type: 'POST' // use POST to avoid IE caching JavaScript data
success: function (data)
{
for (var i = 0; i < data.Data.length; i++)
{
document.getElementById('someelement').innerHTML += '<label id="C' + data.Data[i].ID +'">' + data.Data[i].CompanyName + '</label><br>';
}
}});
}
Related
I am calling a web api and saving the records on the database through the controller, i want each time im calling the api to check if the record exists in the database if yes then dont save, if not then save.
var client = new WebClient();
var text = client.DownloadString("https://www.test.com/api/all-users?name=testusername%20&pass=334432");
var wclients = JsonConvert.DeserializeObject<dynamic>(text);
List<apicli> list1 = new List<apicli>();
var clie = new apicli();
if (wclients.message == "success")
{
var data = wclients.data;
//var account = wclients.account;
ViewBag.test = data;
foreach(var item in ViewBag.test)
{
clie.Email = item.email;
clie.Name = item.name;
clie.Aff = item.affiliated_id;
foreach(var item1 in #item.account.real)
{
clie.Login = item1.login;
clie.password = item1.pass;
}
list1.Add(clie);
db.apiclis.AddRange(list1);
db.SaveChanges();
};
}
I would assume you need something like this, although you need to check what is the unique id of each record:
foreach(var item in data){
var c = new apicli {
Email = item.email,
Name = item.name,
Aff = item.affiliated_id
Login = item.account.real.LastOrDefault()?login??"",
Login = item.account.real.LastOrDefault()?pass??""
}
if(!db.apiclis.Any(a => a.Email == c.Email && a.Name == c.Name && a.Aff == c.Aff)){
db.apiclis.Add(c);
}
}
Here I assume that email+name+aff = unique identificator.
Sort in LINQ
I have 2 database CustomerEntities and BillEntities
I want to get CustomerName from CustomerEntities and sort it but it have no data and I want .ToList() just once time because it slow if used many .ToList()
using (var db1 = new CustomerEntities())
{ using (var db2 = new BillEntities())
{
var CustomerData = db1.Customer.Select(s=> new{s.CustomerCode,s.CustomerName}).ToList();
var BillData = (from t1 in db2.Bill
select new {
BillCode = t1.Billcode,
CustomerCode = t1.Customer,
CustomerName = ""; //have no data
});
}
if(sorting.status==true)
{
BillData= BillData.OrderBy(o=>o.CustomerName); //can't sort because CustomerName have no data
}
var data = BillData .Skip(sorting.start).Take(sorting.length).ToList(); // I want .ToList() just once time because it slow if used many .ToList()
foreach (var b in data)
{
var Customer = CustomerData.FirstOrDefault(f => f.CustomerCode==b.CustomerCode );
if(CustomerName>!=null)
{
r.CustomerName = Customer.CustomerName; //loop add data CustomerName
}
}
}
I have no idea to do it. Help me please
I'm not sure if I understand your code but what about this:
var BillData = (from t1 in db2.Bill
select new {
BillCode = t1.Billcode,
CustomerCode = t1.Customer,
CustomerName = db1.Customer.FirstOrDefault(c => c.CustormerCode == t1.Customer)?.CustomerName
});
Then you have objects in BillData that holds the CustomerName and you can order by that:
BillData.OrderBy(bd => bd.CustomerName);
If you just want to get CustomerName from your customer Db and sort it, this is what i would have used. I used orderByDescending but you can use OrderBy aswell.
public List<Customer> getLogsByCustomerName(string customername)
{
using (var dbentites = new CustomerEntities())
{
var result = (from res in dbentites.Customer.OrderByDescending(_ => _.CustomerName)
where res.CustomerName == customername
select res).ToList();
return result.ToList();
}
}
i need to populate my articles ViewModel with a model that has the database data in it, but i have a method that i need to assign to one of my properties
The list of images is the property that needs the method on it.
The method is called once for every item in the list of articles.
Here is my code:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var query = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName,
}).ToList();
articleViewModel.Images = imageService.GetImagesForArticle(articlemodel.Id.ToString());
return View(query);
}
I have also tried putting the method inside the linq:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var query = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName,
Images = imageService.GetImagesForArticle(a.Id.ToString())
}).ToList();
return View(query);
}
it throws an exception of:
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[New_MinecraftNews_Webiste_MVC.Models.ImageInfo] GetImagesForArticle
I added a foreach loop at the end insted of anything else and it works:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var modelList = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName
}).ToList();
foreach (var model in modelList)
{
model.Images = imageService.GetImagesForArticle(model.Id.ToString());
}
return View(modelList);
}
I have a ControlMeasure table that holds information on each control measure and a ControlMeasurepeopleExposed Table that holds a record for each person exposed in the control measure this could be 1 record or many records.
I Have a controller that populates a List view
For each item in the list, Control Measure, I would like to create a string that shows all the People at risk
e.g.
PeopleString = "Employees, Public, Others";
Ive added a foreach in the controller to show what I'm trying to do however I'm aware that this wont work.
The controller is this:
public ActionResult ControlMeasureList(int raId)
{
//Populate the list
var hazards = new List<Hazard>(db.Hazards);
var controlMeasures = new List<ControlMeasure>(db.ControlMeasures).Where(x => x.RiskAssessmentId == raId);
var cmcombined = (
from g in hazards
join f in controlMeasures
on new { g.HazardId } equals new { f.HazardId }
select new CMCombined
{
Activity = f.Activity,
ControlMeasureId = f.ControlMeasureId,
ExistingMeasure = f.ExistingMeasure,
HazardName = g.Name,
LikelihoodId = f.LikelihoodId,
Rating = f.Rating,
RiskAssessmentId = f.RiskAssessmentId,
SeverityId = f.SeverityId,
}).OrderBy(x => x.Activity).ToList();
var cmPeopleExp = new List<ControlMeasurePeopleExposed>(db.ControlMeasurePeopleExposeds).Where(x => x.RiskAssessmentId == raId);
var peopleExp = from c in cmPeopleExp
join d in db.PeopleExposeds
on c.PeopleExposedId equals d.PeopleExposedId
orderby d.Name
select new RAPeopleExp
{
RAPeopleExpId = c.PeopleExposedId,
PeopleExpId = c.PeopleExposedId,
PeopleExpName = d.Name,
RiskAssessmentId = c.RiskAssessmentId,
ControlMeasureId = c.ControlMeasureId
};
var model = cmcombined.Select(t => new FullControlMeasureListViewModel
{
ControlMeasureId = t.ControlMeasureId,
HazardName = t.HazardName,
LikelihoodId = t.LikelihoodId,
Rating = t.Rating,
SeverityId = t.SeverityId,
Activity = t.Activity,
ExCM = t.ExistingMeasure,
//This section here is where I'm struggling
var PeopleString = new StringBuilder();
foreach (var p in peopleExp)
{
PeopleString.AppendLine(p.PeopleName);
{
PeopleExposed = PeopleString,
});
return PartialView("_ControlMeasureList", model);
}
I know I cant directly put this code in the controller but it does represent what I want to do.
You can't foreach within an object initializer (which is what you're trying to do when instantiating FullControlMeasureListViewModel). You can, however, use a combination of string.Join and peopleExp.Select:
var model = cmcombined.Select(t => new FullControlMeasureListViewModel
{
//other props
PeopleExposed = string.Join(",", peopleExp
.Where(p => p.ControlMeasureId == t.ControlMeasureId)
.Select(p => p.PeopleExpName));
//other props
});
I am working on MVC project where I have successfully created a search page with several dropdowns and textboxes. After the user queries the data, they are then transferred to a List page with a list of results corresponding to our search. I was wondering if it is possible to create a button located on the List view that returns them back to the search page, the search page's textboxes/dropdowns still populated with their previous search. Currently, when they return, their previous search was cleared, and they can't see what was queried.
Simplified: Is there a way to capture the data of a viewmodel on query submit, and then be able to access it with simple return button.
Get Method (populates dropdown etc)
[HttpGet]
public ActionResult Index()
{
//testTypes
var testTypesL = new List<string>();
var testTypesQr = from z in db.Results
orderby z.TestType
select z.TestType;
testTypesL.AddRange(testTypesQr.Distinct());
//technicians
var techniciansL = new List<string>();
var techniciansQr = from z in db.Results
orderby z.Technician
select z.Technician;
techniciansL.AddRange(techniciansQr.Distinct());
//engineers
var engineersL = new List<string>();
var engineerQr = from z in db.Results
orderby z.Engineer
select z.Engineer;
engineersL.AddRange(engineerQr.Distinct());
//testStalls
var testStallL = new List<string>();
var testStallQr = from z in db.Results
orderby z.TestStall
select z.TestStall;
testStallL.AddRange(testStallQr.Distinct());
//unit models
var unitModelL = new List<string>();
var unitModelQr = from z in db.Results
orderby z.UnitID
select z.UnitID;
unitModelL.AddRange(unitModelQr.Distinct());
TestDataViewModel obj = new TestDataViewModel();
obj.EngineerList = new SelectList(engineersL);
obj.TechnicianList = new SelectList(techniciansL);
obj.TestStallList = new SelectList(testStallL);
obj.UnitModelList = new SelectList(unitModelL);
obj.TestTypeList = new SelectList(testTypesL);
return View("Index", obj);
}
Post Method: (sends user query to the List view)
[HttpPost]
public ActionResult Index(TestDataViewModel obj)
{
var data = from d in db.Results
select d;
//search data parameters
if (!String.IsNullOrEmpty(obj.StartDate.ToString()) && !String.IsNullOrEmpty (obj.EndDate.ToString()))
{
data = data.Where(z => obj.StartDate <= z.EndDate && obj.EndDate >= z.EndDate);
}
if (!String.IsNullOrEmpty(obj.TestNumber.ToString()))
{
data = data.Where(z => z.TestNumber == obj.TestNumber);
}
if (!String.IsNullOrEmpty(obj.unitModel))
{
data = data.Where(z => z.UnitID == obj.unitModel);
}
if (!String.IsNullOrEmpty(obj.Project))
{
data = data.Where(z => z.ProjectNum.Contains(obj.Project));
}
if (!String.IsNullOrEmpty(obj.testType))
{
data = data.Where(z => z.TestType == obj.testType);
}
if (!String.IsNullOrEmpty(obj.engineer))
{
data = data.Where(z => z.Engineer == obj.engineer);
}
if (!String.IsNullOrEmpty(obj.technician))
{
data = data.Where(z => z.Technician == obj.technician);
}
if (!String.IsNullOrEmpty(obj.testStall))
{
data = data.Where(z => z.TestStall == obj.testStall);
}
return View("List", data);
}