How can I save a viewmodel for postback viewing? - c#

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

Related

Problem returning entity grouped with LINQ in HTTP GET

What I'm doing wrong in this method below? I created a group with linq because I need to group the list by 2 columns and for this grouping I will have a list of files.
[HttpGet]
[Route("versions-by-period")]
public IActionResult GetVersionsByPeriodId(int entityId, int periodId)
{
var versionsInvoiceBillet = db.RemittanceInvoiceBilletVersionsCompacts
.Where(x => x.LegalEntityId == entityId && x.PeriodId == periodId && x.IsCurrent && x.DownloadHash != null)
.GroupBy(x => new { x.LifePolicyNumber, x.LegalEntityGroupNumber },
i => new { i.DownloadHash, i.FileTypeEnum, i.DueDate }, (key, group) => new
{
LifePolicyNumber = key.LifePolicyNumber,
LegalEntityGroupNumber = key.LegalEntityGroupNumber,
Files = group.ToList()
});
return Ok(versionsInvoiceBillet.Select(x => new {
lifePolicyNumber = x.LifePolicyNumber,
legalEntityGroupNumber = x.LegalEntityGroupNumber,
invoiceAndBillet = x.Files.Select(f => new {
downloadHash = f.DownloadHash,
fileTypeEnum = f.FileTypeEnum,
dueDatet = f.DueDate
})
}));
}
If I try to call this method with Postman, the body comes empty. The problem is in invoiceAndBillet information that is returned, if I change to below, the body comes filled.
return Ok(versionsInvoiceBillet.Select(x => new {
lifePolicyNumber = x.LifePolicyNumber,
legalEntityGroupNumber = x.LegalEntityGroupNumber,
invoiceAndBillet = x.Files.Select
}));
If I try to debug the selection that I'm trying to return, I get this message below:

Checking for existing records on database wen i call web api

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.

How to check items of a table based on the defined access for user?

I have two tables containing following columns:
SELECT TOP 1000 [Id]
,[UserId]
,[MenuId]
,[parentid]
FROM [TravelEnterDB].[dbo].[UserAccess]
SELECT TOP 1000 [Id]
,[Title]
,[parentId]
,[IsActive]
,[Url]
,[OrderMenu]
,[IconName]
FROM [TravelEnterDB].[dbo].[AdminMenu]
so here is the deal,i want to show all of the 'AdminMenu' records with 'parenId=0' in a table in MVC and i want to tick the items which have been given to a specific user by 'UserId'.I have some codes but they are not working correctly.
Here is the code:
public ActionResult ADDAccess(int? id, string UserId)
{
List<MenuClass> model = new List<MenuClass>();
var result =(from adminMenu in db.AdminMenus
where adminMenu.parentId == 0
select new
{
adminMenu.Id,
adminMenu.IsActive,
adminMenu.OrderMenu,
adminMenu.Title,
adminMenu.Url,
adminMenu.parentId,
adminMenu.IconName,
});
var users = db.UserAccesses.Where(p => p.UserId == UserId).ToList();
var t = (from m in users
join r in result on m.MenuId equals r.Id
select new
{
r.Id,
r.IsActive,
r.OrderMenu,
r.Title,
r.Url,
r.parentId,
r.IconName,
m.UserId,
m.MenuId
}).ToList();
foreach (var item in t)
{
MenuClass menu = new MenuClass();
menu.IconName = item.IconName;
menu.IsActive = item.IsActive;
menu.Title = item.Title;
menu.Url = item.Url;
menu.Id = item.Id;
if (item.Id == item.MenuId && item.UserId == UserId)
{
menu.IsChecked = true;
}
menu.parentId = (int)item.parentId;
model.Add(menu);
}
return View(model);
}

Populate a view model with a data model with a method aswell

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

StringBuilder within IEnumerable

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

Categories

Resources