Querying data from Table and passing to view - asp.net

Need help with this coding.
Here I want to get request details from the main request table which is called "AppRequest". Here I have queried some requests and need to load the main details of the request from the AppRequest table. In the "ListRequesDropDown" is getting the main request ids from the AppRequest. So I want to pass that request-id data to the view. Currently "return View(db.AppRequest.ToList());" will shows the all the requests.
public class PendingRequestMController : Controller
{
private zSqlDb db = new zSqlDb();
// GET: PendingRequests to manager view
public ActionResult Index()
{
//Checking User ID
var UsrID = (User.Identity as ClaimsIdentity).Claims.Where(c => c.Type == "UserId").FirstOrDefault();
string UsrIDT = UsrID.Value;
// Checking is there any pending request to the above user ID
List <int> PendingRequestsforAprv = db.ApproveParties.ToList().Where(r => r.Approver_Id == int.Parse(UsrIDT ) && r.Approve_Status==false).ToList().
Select(x => x.ApprovalProcess_Id).ToList();
List<int> ReqTypeDropDown = db.ApprovalProcess.Where(r => PendingRequestsforAprv.Contains( r.Id )).Select(x => x.Req_Id).ToList();
return View(db.AppRequest.ToList());
}
}

Related

Updating records on different tables ASP.NET MVC

In my application from the view someone pressed the Approve button, controller will collect the Main Id of the request. Here I want to update 3rd table Approval_Status column to true. I passed the main Id and got the 3rd table Id which I want to update record to the variable.
int PartyId = db.ApprovalProcess.Where(x => x.Req_Id == id).ToList().First().Id;
and then I wrote this code to pass the value. But it wont work. Can I get a help for this (question will seems like easy to you, but i want to tell you that I'm self learning ASP.NET MVC these days. So some stuff still I couldn't get)
Here is my database structure. Main table name is AppRequest, 2nd table is ApprovalProcess and the 3rd one is Approval_Parties.
This is my current code:
public ActionResult ApproveRequest(int? id)
{
int PartyId = db.ApprovalProcess.Where(x => x.Req_Id == id).ToList().First().Id;
if (ModelState.IsValid)
{
// model.Approved_Date = DateTime.Now;
ApprovalParty approvalParty = new ApprovalParty();
approvalParty.Approve_Status = true;
db.SaveChanges();
return RedirectToAction("Index");
}
}
I think I'm missing the code that which record should update in the table that already assigned that Id to the PartyId.
Something like this would work:
public ActionResult ApproveRequest(int? id)
{
ApprovalProcess approvalProcess = db.ApprovalProcess.FirsOrDefault(x => x.Req_Id == id);
if (approvalProcess != null)
{
ApprovalParty approvalParty = db.Approval_Parties.FirsOrDefault(x => x.ApprovalProcess_Id == approvalProcess.Id);
if (approvalParty != null)
{
approvalParty.Approve_Status = true;
approvalParty.Approved_Date = DateTime.Now;
db.SaveChanges();
return RedirectToAction("Index");
}
}
}

Get value from IActionResult

I have Controller whit some endpoints Task<IActionResult> MyCustomEndpoint which is returning return Ok(CustomDataType). Returned datas are in JSON fromat.
Now I want to call that Endpoint from other Controller like var resp = myController.MyCustomEndpoint, where resp becomes IActionResult. The problem is that resp now doesn't return only datas anymore, but all of those fields as seen on image.
My question is, how to access and return only Value field, because resp.Value is not working.
Thanks for help.
You have to convert to as ObjectResult
public async Task GetFormSummary_ItShouldReturnSingleForm_NotNull()
{
var formId = new Guid("5EF685E7-1167-4226-7F5E-08D9009544A3");
var mockFormService = new Mock<IFormService>();
mockFormService.Setup(x => x.GetAsync(formId).Result)
.Returns(GetTestForm());
// Inject
var formController = new FormController(_logger, mockFormService.Object);
// Act
var result = (await formController.GetAsync(formId)) as ObjectResult;
// Assert
Assert.IsAssignableFrom<FormViewModel>(result.Value);
}

Saving current user name(logged) into Form database ASP.Net MVC

I am newbie in ASP.NET. Is there a possible way to save the current logged user into the form database when the form is submitted?
(i.e) When multiple registered users enter a form and click save their user name is saved into the contents of form database.
I had googled it but couldn't find related topics (maybe I used the wrong keywords). If methods are available kindly suggest link.
[Edit]
I have used asp.net identity for authentication.
My current code for save
public ActionResult NewPR()
{
var depts = _context.Depts.ToList();
var currencytypes = _context.Currencytypes.ToList();
var viewModel = new NewPRViewModel
{
PRview = new PRview(),
Currencytypes = currencytypes,
};
return View("NewPR", viewModel);
}
[HttpPost]
public ActionResult Save(PRview prview)
{
if (!ModelState.IsValid)
{
var viewModel = new NewPRViewModel
{
PRview = prview,
Currencytypes = _context.Currencytypes.ToList()
};
return View("NewPR", viewModel);
}
if (prview.Id == 0)
_context.PRviews.Add(prview);
else
{
var prviewInDb = _context.PRviews.Single(c => c.Id == prview.Id);
prviewInDb.SupplierName = prview.SupplierName;
prviewInDb.Brand = prview.Brand;
prviewInDb.Qty = prview.Qty;
prviewInDb.Unitprice = prview.Unitprice;
}
_context.SaveChanges();
return RedirectToAction("Index", "PRview");
}

asp.net web api 2 LINQ to Entities does not recognize the method

I want to invoke method durning mapping my domain class to DTO class but after many tries with LINQ to Entities or LINQ to objects i have failed and i'm getting weird different errors. Actulal error is just a "LINQ to Entities does not recognize the method 'System.String ResizeToLogoImage(System.String)' method, and this method cannot be translated into a store expression.".
Mapping method:
public async Task<SingleCategory> SingleCategoryMapping(EventerApiContext context, int id)
{
var category = await context.Category.Select(c => new SingleCategory
{
CategoryId = c.CategoryId,
CategoryName = c.CategoryName,
CityId = c.CityId,
Events = context.Event.ToList().Where(e=>e.CategoryId == id).Select(e=> new EventForSingleCategory
{
EventId = e.EventId,
EventName = e.EventName,
EventLogo = ImageProcessor.ResizeToLogoImage(e.EventDetail.EventImage.EventImageBase64)
}).ToList()
}).SingleOrDefaultAsync(c => c.CategoryId == id);
return category;
}
Method to be invoked.
public static string ResizeToLogoImage(string base64String)
{
if (base64String == null)
{
return "NULL";
}
var imageToResize = Base64ToImage(base64String);
var resizedImage = ScaleImage(imageToResize, 50, 50);
return ImageToBase64(resizedImage, imageToResize.RawFormat);
}
I know error is appearing during EventLogo property mapping but i have no more idea what to do.
Try to get the data first, before you do the Select statement. I suspect that it is trying to execute ResizeToLogoImage on the database :)

Showing linked table items in a controller/view

I have a room class, which has 3 linked tables, Property, Sex (as in Male/Female), Stage.
I can get the Index controller to return the linked table items, by using Include:
var rooms = db.Rooms.Include(r => r.Property).Include(r => r.Sex).Include(r => r.Stage);
What I don't know is, how to you include these linked table items in the Details controller:
Room room = db.Rooms.Find(id);
The full controllers are listed below:
//
// GET: /Room/
public ActionResult Index()
{
var rooms = db.Rooms.Include(r => r.Property).Include(r => r.Sex).Include(r => r.Stage);
return View(rooms.ToList());
}
//
// GET: /Room/Details/5
public ActionResult Details(int id = 0)
{
Room room = db.Rooms.Find(id);
if (room == null)
{
return HttpNotFound();
}
return View(room);
}
Thanks for any help,
Mark
After Include statments you could use LINQ's SingleOrDefault method
Like this:
Room room = db.Rooms.Include(r => r.Property)
.Include(r => r.Sex)
.Include(r => r.Stage)
.SingleOrDefault(r => r.Id = id);

Resources