How can I pass values to the URL in ASP.NET Core 6 MVC? - asp.net-core

I am trying to pass an Id from one controller to another by passing the value in the url and calling it in the other controller. So far I have tried everything and I can't get it to work. Can anyone help?
Here is the flight controller
[HttpGet]
public IActionResult SearchFlights(string origin, string destination, DateTime departureDate)
{
var flights = _context.Flights
.Where(f => f.DepartureAirport == origin
&& f.ArrivalAirport == destination
&& f.DepartureDatetime.Date == departureDate.Date)
.ToList();
ViewBag.Origin = origin;
ViewBag.Destination = destination;
ViewBag.DepartureDate = departureDate;
return View(flights);
}
[HttpPost]
public IActionResult SearchFlights(int flightId)
{
string url = string.Format("/Reservation/AddPassenger?flightId={0}", flightId);
return Redirect(url);
}
Here is the ReservationController:
[HttpGet]
public IActionResult AddPassenger([FromRoute] int flightId)
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddPassenger(Passenger passanger, [FromRoute] int flightId)
{
Passenger passenger = new Passenger()
{
Name = passanger.Name,
Email = passanger.Email,
PhoneNumber = passanger.PhoneNumber,
PassportNumber = passanger.PassportNumber,
PaymentMethod = passanger.PaymentMethod,
};
_context.Passengers.Add(passenger);
_context.SaveChanges();
int passengerId = passenger.PassengerId;
Reservation reservation = new Reservation()
{
FlightId = flightId,
SeatId = 2,
PassengerId = passengerId,
ReservationStatus= "Confirmed",
ReservationDate= DateTime.Now,
};
_context.Reservations.Add(reservation);
_context.SaveChanges();
return RedirectToAction("Index");
}
Essentially this is a search mechanism to display the data when the user clicks book the ID should be sent to the Url, but it doesn't, the url in the browser is like this
https://localhost:2213/Reservation/AddPassenger?.
Am I doing something wrong?

If you want to pass value from one controller to another controller in .netcore, I have a suggestion like below:
Try to use TempData:
In flight controller:
[HttpPost]
public IActionResult SearchFlights(int flightId)
{
TempData["flightId"] = flightId;
return RedirectToAction("AddPassenger", "Reservation");
}
And in Reservation Controller:
[HttpGet]
public IActionResult AddPassenger()
{
var flightId = TempData["flightId"];
return View();
}
result:
Or
Just Remove the [FromRoute]
[HttpGet]
public IActionResult AddPassenger( int flightId)
{
return View();
}
result:

Related

add update and delete product methods not working in postman and not making any change in my database

services.AddAuthorization(options =>
{
options.AddPolicy("RequireLoggedIn", policy => policy.RequireRole("Admin", "Customer", "Moderator").RequireAuthenticatedUser());
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Admin").RequireAuthenticatedUser());
});
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NG_Core_Auth.Data;
using NG_Core_Auth.Models;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace NG_Core_Auth.Controllers
{
[Route("api/[controller]")]
public class ProductController : Controller
{
private readonly ApplicationDbContext _db;
public ProductController(ApplicationDbContext db)
{
_db = db;
}
// GET: api/values
[HttpGet("[action]")]
[Authorize(Policy = "RequireLoggedIn")]
public IActionResult GetProducts()
{
return Ok(_db.Products.ToList());
}
[HttpPost("[action]")]
[Authorize(Policy = "RequireAdministratorRole")]
public async Task<IActionResult> AddProduct([FromBody] ProductModel formdata)
{
var newproduct = new ProductModel
{
Name = formdata.Name,
ImageUrl = formdata.ImageUrl,
Description = formdata.Description,
OutOfStock = formdata.OutOfStock,
Price = formdata.Price
};
await _db.Products.AddAsync(newproduct);
await _db.SaveChangesAsync();
return Ok(new JsonResult("The Product was Added Successfully"));
}
[HttpPut("[action]/{id}")]
[Authorize(Policy = "RequireAdministratorRole")]
public async Task<IActionResult> UpdateProduct([FromRoute] int id, [FromBody] ProductModel formdata)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var findProduct = _db.Products.FirstOrDefault(p => p.ProductId == id);
if (findProduct == null)
{
return NotFound();
}
// If the product was found
findProduct.Name = formdata.Name;
findProduct.Description = formdata.Description;
findProduct.ImageUrl = formdata.ImageUrl;
findProduct.OutOfStock = formdata.OutOfStock;
findProduct.Price = formdata.Price;
_db.Entry(findProduct).State = EntityState.Modified;
await _db.SaveChangesAsync();
return Ok(new JsonResult("The Product with id " + id + " is updated"));
}
[HttpDelete("[action]/{id}")]
[Authorize(Policy = "RequireAdministratorRole")]
public async Task<IActionResult> DeleteProduct([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// find the product
var findProduct = await _db.Products.FindAsync(id);
if (findProduct == null)
{
return NotFound();
}
_db.Products.Remove(findProduct);
await _db.SaveChangesAsync();
// Finally return the result to client
return Ok(new JsonResult("The Product with id " + id + " is Deleted."));
}
}
}
I work the controller with add update and delete methods I run the application and it run successfully with https://localhost:44301/ url then I make all the steps correctly in postman by adding https://localhost:44301/api/product/addproduct, putting headers and put the data I want to insert it in the body row and use post method I click send it return 401 Unauthorized, what is the problem ?
Iposted Productcontroller.cs and part of startup.cs files
Try to do a POST in Postman to your Login endpoint first. This will give the cookie to Postman that you are logged in (and what roles you have). Then next you should be able to POST successfully to your endpoints with Authorize attributes

How can i get specific user from identity server - aspNetUsers table depdening on his id

I try to get one specific user from the AspNetUsers table but without success in ASP.Net Core.
Here is the code that i try:
[HttpGet]
[Route("employee/{id}")]
public async Task<Object> GetSpecificUser(string id)
{
var user = await _userManager.FindByIdAsync(id);
return Ok(user);
}
// and
[HttpGet]
[Route("employee/{id}")]
public IActionResult GetSpecificUser(string id)
{
var user = _userManager.Users.FirstOrDefault(x => x.Id == id);
return Ok(user);
}

.Net Core 2.0 Web API controller not working and getting 404

I have something very very strange. I have 2 controllers. UploadController and AccountController. Theye were both working, and now when I try the AccountController it give error 404. ik don't get it.
This is how my AccountController looks like:
namespace CoreAngular.Controllers
{
//[Authorize]
[Produces("application/json")]
[Route("api/account")]
public class AccountController : Controller
{
private IRepository repository;
public AccountController(IDatabaseClient<DocumentClient> client)
: this ( new UserRepository(client))
{
}
public AccountController(IRepository repository)
{
this.repository = repository;
}
[HttpGet]
public async Task<ActionResult> Get(string id)
{
var start = DateTime.Now.TimeOfDay;
if (string.IsNullOrEmpty(id))
{
return BadRequest();
}
var user = await repository.GetAsync(id);
if (user == null)
{
return NotFound();
}
var userDTO = new UserGetDTO()
{
image = Convert.ToBase64String(user.image.image),
id = user.id,
time = DateTime.Now.Subtract(start).Millisecond
};
return Ok(userDTO);
}......
Do I miss something here? I know I comentet out the [Authorize], but i just wanted to try to connect.
You should specify route template in HttpGet attribute:
[HttpGet("{id}")]
public async Task<ActionResult> Get(string id)
{
// ...
}

asp.net mvc 4. 0 - multiple action to render data to same view

How i can overload actions in a controller.
public ActionResult OnlineHome()
{
OnlineDataModel dm = new OnlineDataModel();
dm.CatagoryData = new List<category>();
dm.ProductData = new List<product>();
dm.CatagoryData = db.categories.ToList();
return View(dm);
}
[HttpPost]
public ActionResult OnlineHome(int CategoryId)
{
OnlineDataModel dm = new OnlineDataModel();
dm.CatagoryData = new List<category>();
dm.ProductData = new List<product>();
dm.CatagoryData = db.categories.ToList();
Convert.ToInt32(CategoryId) select p).ToList() ;
var data= db.products.Where(d => d.CategoryID == CategoryId).ToList();
dm.ProductData = data.ToList();
ViewBag.data = data;
return View(dm);
}
[HttpPost]
public ActionResult OnlineHome(OnlineDataModel data)
{
return View();
}
please help. how i can overload the actions which will render data to same view
You can use the ActionName attribute if you want your code to do overloading.
[ActionName("MyOverloadedName")]
To Render the Same View, You can pass the Model and ViewName like this.
return View("ViewName",model);
you can provide ActionName attribute with different name while calling it from View. Like
[ActionName("OnlineHomeWithCategoryId")]
public ActionResult OnlineHome(int CategoryId)
{
}
[ActionName("OnlineHomeWithData")]
public ActionResult OnlineHome(OnlineDataModel data)
{
}
Now you just need to use these action names while calling these action metho

Update div after POST method

I have a page with a form for registering a new user. After pressing the submit button the following action method (which checks if a user is already in DB and inserts a new one if there isn't) executes in my controller.
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model)
{
int result = this.isUserInDB(model.Email);
ViewBag.numberOfEmails = result;
if (result == 0)
{
this.insertNewUserInDB(model.Name, model.Surname, model.Password, model.Email);
}
return View();
}
Now I would like to have a div, on the same page as the form, where I would display a notification message if:
a user is already in the db
a user was inserted in the db
I can't accomplish this now, because I always return the same view. I tried changin the return type of the action method to void, but that displays a blank page.
How can I solve this? Thank you in advance.
I can't accomplish this now, because I always return the same view.
That's not a problem. In your view you could have some conditional logic:
if (Model.NewUserInserted)
{
<div>A new user was created</div>
}
else if (Model.UserAlreadyExists)
{
<div>The specified user already exists</div>
}
of course you should now write your view model:
public class MyViewModel
{
public int NumberOfEmails { get; set; }
public bool NewUserInserted { get; set; }
public bool UserAlreadyExists { get; set; }
}
the controller action that is initially rendering this view should pass an empty model:
return View(new MyViewModel());
and your POST action should set the corresponding properties:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model)
{
int result = this.isUserInDB(model.Email);
var viewModel = new MyViewModel();
viewModel.NumberOfEmails = result;
if (result == 0)
{
this.insertNewUserInDB(model.Name, model.Surname, model.Password, model.Email);
viewModel.NewUserInserted = true;
}
else
{
viewModel.UserAlreadyExists = true;
}
return View(viewModel);
}
and of course your view should be strongly typed to the view model:
#model MyViewModel
and you should get rid of all ViewBag.