passing data(Id) with redircetToAction to url using ViewModel - asp.net-mvc

hello I'm trying to pass the new posted value to a different view with the new value id at the url using RedirectToAction but I'm getting the wrong Url .
Just like here in SO ,that you get redirect to your Q. after submit.
the Url I'm suppose to get is http://localhost:1914/en/evntes/index/60
MyCode(Controler= VoosUp)
public ActionResult Create()
{
var viewModel = new LectureFormViewModel
{
Genres = _context.Genres.ToList(),
};
return View("Gigform", viewModel);
}
[Authorize, HttpPost]
public ActionResult Create(LectureFormViewModel viewModel)
{
if (!ModelState.IsValid)
{
viewModel.Genres = _context.Genres.ToList();
return View("Gigform", viewModel);
}
var lectureGig = new LectureGig
{
//Prametrest
};
_context.LectureGigs.Add(lectureGig);
_context.SaveChanges();
// return this.RedirectToAction( "events", (c=>c.Index(lectureGig.Id)); //Compiler Error
return RedirectToAction("index", "Events", new { id = lectureGig.Id });//Ok Id 60
}
Events/Index
public ActionResult Index(int id)//OK id=60
{
var lecturegig = _context.LectureGigs.Include(g => g.Artist)
.Include(g => g.Genre)
.SingleOrDefault(g => g.Id == id);
if (lecturegig == null)
return HttpNotFound();
var viewmodel = new GigDetailViewModel { LectureGig = lecturegig };
return View("index", viewmodel);
}
Url i'm getting :http://localhost:1914/en/VoosUp/Create
and the view is correct

Related

How can I return Id when model state cannot be work?

I am in "User Add" page. I have an Id which coming from "Visa Type" page.
When my page cannot be pair with model state, the Id doesn't exist in the URL. I need this Id. How can I return again?
Controller
[HttpGet]
public IActionResult AddUser(int visaTypeId)
{
ViewBag.Id = visaTypeId;
Guid g = Guid.NewGuid();
ViewBag.UniqueUser = g;
return View();
}
[HttpPost]
public async Task<IActionResult> AddUser(UserModel userModel, string uniqueUser, int visaTypeId)
{
if (ModelState.IsValid)
{
var result = await _client.PostAsJsonAsync<UserModel>("users/adduser", userModel);
var response = await result.Content.ReadAsStringAsync();
var responseModel = JsonConvert.DeserializeObject<ResponseModel>(response);
if (responseModel.Success == false)
{
//ViewBag.Message = responseModel.Message;
ModelState.AddModelError("", responseModel.Message);
}
if (result.IsSuccessStatusCode)
{
return RedirectToAction("AddApplicant", "Applicant", new { uniqueUser = uniqueUser });
}
}
return View();
}
You can pass back whatever you obtain from your view.
[HttpPost]
public async Task<IActionResult> AddUser(UserModel userModel, string uniqueUser, int visaTypeId)
{
if (ModelState.IsValid)
{
var result = await _client.PostAsJsonAsync<UserModel>("users/adduser", userModel);
var response = await result.Content.ReadAsStringAsync();
var responseModel = JsonConvert.DeserializeObject<ResponseModel>(response);
if (responseModel.Success == false)
{
//ViewBag.Message = responseModel.Message;
ModelState.AddModelError("", responseModel.Message);
}
if (result.IsSuccessStatusCode)
{
return RedirectToAction("AddApplicant", "Applicant", new { uniqueUser = uniqueUser });
}
}
ViewBag.VisaTypeId = VisaTypeId;
ViewBag.uniqueUser = uniqueUser;
return View(userModel);
}

Property field return nulls

My server/client side application has following controllers. However when I post/create a reservation, it does not the hold/cache the value of (id) property return (CreatedAtAction(nameof(GetById), new{id=order.id}, order} method, when post action goes out of scope. Therefore GetById(int id) does not receive last id generated rather shows 0. However data commits successfully in the database with valid id.
Server side controller:
[HttpGet("{id:int}")]
public ActionResult<OrderTable> GetById(int id)
{
var order = _context.ReservationsTables.FirstOrDefault(o => o.Id == id);
if(order == null)
{
return NotFound();
}
else
{
return order;
}
}
[HttpPost]
public ActionResult<OrderTable> CreateOrder(OrderTable order)
{
_context.ReservationsTables.Add(order);
_context.SaveChanges();
return CreatedAtAction(nameof(GetById), new { id = order.Id }, order);
}
Client Side controller:
public async Task<IActionResult> CreatePostAsync(OrderTable order)
{
var httpClient = _clientFactory.CreateClient();
HttpResponseMessage response = await httpClient.PostAsJsonAsync("https://localhost:44387/api/Reservation", order);
if (response.IsSuccessStatusCode)
{
var orderResult = await response.Content.ReadAsAsync<OrderTable>();
return RedirectToAction("ThankYouAsync", new { id = order.Id });
}
else
{
return View("An error has occurred");
}
}
public async Task<IActionResult> ThankYouAsync(int orderId)
{
var httpClient = _clientFactory.CreateClient();
httpClient.BaseAddress = new Uri("https://localhost:44387/");
HttpResponseMessage response = await httpClient.GetAsync("api/Reservation/" + orderId);
if (response.IsSuccessStatusCode)
{
var orderResult = await response.Content.ReadAsAsync<OrderTable>();
return View(orderResult);
}
else
{
return View("An error has occurred");
}
}
[HttpGet]
public async Task<IActionResult> Create()
{
await PopulateRestaurantDropDownListAsync();
return View();
}
The redirected action has the following signature
Task<IActionResult> ThankYouAsync(int orderId)
Note that the parameter name is orderId.
Yet when the redirection is done,
return RedirectToAction("ThankYouAsync", new { id = order.Id });
the value object is defined new { id = order.Id }
The parameter names need to match for it to work as expected.
So update RedirectToAction to use the correct property name
return RedirectToAction("ThankYouAsync", new { orderId = order.Id });
Note the new { orderId = order.Id } in the value object with matching orderId parameter.

Mvc5 Error Please :( [duplicate]

This question already has answers here:
The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
(6 answers)
Closed 5 years ago.
Hello Everybody Good day My English is not very good Poo Do not Look Mvc 5 New Start My Blog Site.
I got the error
I List Categories, I Provide Entrance to Other Areas
When I Select Photo When I Select Time
I uploaded the picture and I share the link. I am taking this mistake. Could you show me the way to this error? Thank you for your time
namespace MvcSite.Controllers
{
public class AdminMakaleController : Controller
{
MvcblogDb db = new MvcblogDb();
// GET: AdminMakale
public ActionResult Index()
{
var makale = db.Makale.ToList();
return View(makale);
}
// GET: AdminMakale/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: AdminMakale/Create
public ActionResult Create()
{
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi");
return View();
}
// POST: AdminMakale/Create
[HttpPost]
public ActionResult Create(Makale makale, string Etiket, HttpPostedFile Foto)
{
if (ModelState.IsValid)
{
if (Foto != null)
{
WebImage img = new WebImage(Foto.InputStream);
FileInfo fotoinfo = new FileInfo(Foto.FileName);
string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension;
img.Resize(800, 350);
img.Save("~/Uploads/MakaleFoto/" + newfoto);
makale.Foto = "/Uploads/MakaleFoto/" + newfoto;
}
if (Etiket != null)
{
string[] etiketdizi = Etiket.Split(',');
foreach (var i in etiketdizi)
{
var yenietiket = new Etiket { EtiketAdi = i };
db.Etiket.Add(yenietiket);
makale.Etiket.Add(yenietiket);
}
}
db.Makale.Add(makale);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
// GET: AdminMakale/Edit/5
public ActionResult Edit(int id)
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makales == null)
{
return HttpNotFound();
}
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi", makales.KategoriId);
return View(makales);
}
// POST: AdminMakale/Edit/5
[HttpPost]
public ActionResult Edit(int id, HttpPostedFile Foto, Makale makale)
{
try
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (Foto != null)
{
if (System.IO.File.Exists(Server.MapPath(makales.Foto)))
{
System.IO.File.Delete(Server.MapPath(makales.Foto));
}
WebImage img = new WebImage(Foto.InputStream);
FileInfo fotoinfo = new FileInfo(Foto.FileName);
string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension;
img.Resize(800, 350);
img.Save("~/Uploads/MakaleFoto/" + newfoto);
makale.Foto = "/Uploads/MakaleFOTO/" + newfoto;
makales.Baslik = makale.Baslik;
makales.İcerik = makale.İcerik;
makales.KategoriId = makale.KategoriId;
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi", makale.KategoriId);
return View(makale);
}
}
// GET: AdminMakale/Delete/5
public ActionResult Delete(int id)
{
var makale = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makale == null)
{
return HttpNotFound();
}
return View(makale);
}
// POST: AdminMakale/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makales == null)
{
return HttpNotFound();
}
if (System.IO.File.Exists(Server.MapPath(makales.Foto)))
{
System.IO.File.Delete(Server.MapPath(makales.Foto));
}
foreach (var i in makales.Yorum.ToList())
{
db.Yorum.Remove(i);
}
foreach (var i in makales.Etiket.ToList())
{
db.Etiket.Remove(i);
}
db.Makale.Remove(makales);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Try to use a DropDownListFor instead of a DropdownList. The error you mention means that you are having NULL in the SelectListItem. You should create a list of ListItem in the DropDownList.
(I'm not sure if I'm correct or not. I'm just trying to help quickly.)

Making Sessions in MVC 6 Controller(with views, using Entity Framework)

I'm attempting to create a session in my UserAccountsController
using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using POPPELWebsite.Models;
namespace POPPELWebsite.Controllers
{
public class UserAccountController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(UserAccount account)
{
if (ModelState.IsValid)
{
using (OurDbContext db = new OurDbContext())
{
db.userAccount.Add(account);
db.SaveChanges();
}
ModelState.Clear();
ViewBag.Message = account.FirstName + " " + account.LastName + " successfully registered.";
}
return View();
}
//Login
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(UserAccount user)
{
using (OurDbContext db = new OurDbContext())
{
var usr = db.userAccount.Single(u => u.Email == user.Email && u.Password == user.Password);
if (usr != null)
{
Session["UserID"] = usr.UserID.ToString;
}
}
}
}
}
I get an error saying
the name Session does not exist in the current context.
I need to do this part to complete a registration and login tutorial for mvc
The Session property does not exist in the Controller class in MVC 6, instead use HttpContext.Session to access the session property.
Ex:
// get values
string strValue = HttpContext.Session.GetString("StringKey");
int intValue = HttpContext.Session.GetInt32("IntKey");
byte[] byteArrayValue = HttpContext.Session.Get("ByteArrayKey");
// set values
HttpContext.Session.Set("ByteArrayKey", byteArrayValue);
HttpContext.Session.SetInt32("IntKey", intValue);
HttpContext.Session.SetString("StringKey", strValue);
Try this.
public ActionResult Login(User users)
{
if (ModelState.IsValid)
{
using (DataContext db = new DataContext())
{
var obj = db.Users.Where(u => u.Username.Equals(users.Username) && u.Password.Equals(users.Password)).FirstOrDefault();
if(obj !=null)
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
context.Session["UserId"] = obj.UserId.ToString();
context.Session["Username"] = obj.Username.ToString();
return RedirectToAction("Dashboard");
}
}
}
return View(users);
}

I am not able to get the User.Identity.Name after redirected from controller in Mvc

In the 1st example:-
i am assigning User.Identity.Name value to the variable id. i am able to get the value after that i am Redirecting to some other view here i am using Redirect(ReturnUrl) now i am able to get the User.Identity.Name value in the other controller(Redirected view) also
But in the 2nd example :-
i am assigning User.Identity.Name value to the variable id i am able to get the value after that i am Redirecting to some other view here i am using return Redirect(ReturnUrl);when i am using return Redirect(ReturnUrl);am not able to get the User.Identity.Name value in the Redirected url
Example 1:-
public ActionResult SignIn(string ReturnUrl)
{
if (ReturnUrl == "/" || string.IsNullOrEmpty(ReturnUrl))
{
ReturnUrl = "/Dashboard";
}
var id=HttpContext.Current.User.Identity.Name;
Response.Redirect(ReturnUrl);
return View();
}
Example 2:-
public ActionResult SignIn(string ReturnUrl)
{
if (ReturnUrl == "/" || string.IsNullOrEmpty(ReturnUrl))
{
ReturnUrl = "/Dashboard";
}
var id=HttpContext.Current.User.Identity.Name;
return Redirect(ReturnUrl);
}
My Controller:- In this function if i am return Redirect(ReturnUrl); i am not able to get the User.Identity.Name value in CompanyRequired filter if i am using Response.Redirect(ReturnUrl); return View(); then able to get the User.Identity.Name value in CompanyRequired filter but i have to use return Redirect(ReturnUrl);
[HttpPost]
public async Task<ActionResult> SignInCallback()
{
var token = Request.Form["id_token"];
var state = Request.Form["state"];
var claims = await ValidateIdentityTokenAsync(token, state);
string ReturnUrl = state.Substring(state.IndexOf('?') + 1);
var id = new ClaimsIdentity(claims, "Cookies");
Request.GetOwinContext().Authentication.SignIn(id);
if (ReturnUrl == "/" || string.IsNullOrEmpty(ReturnUrl))
{
ReturnUrl = "/Dashboard";
}
var Id = User.Identity.Name;
return Redirect(ReturnUrl);
}
View:- Here i control will go to the CompanyRequired filter there i need a User.Identity.Name value in that i am getting value null
[Authorize,CompanyRequired]
public class DashBoardController : BaseController
{
public ActionResult Index()
{
return View();
}
}
CompanyRequired Filter:-
public class CompanyRequiredAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var coCookie = filterContext.HttpContext.Request.Cookies["CoId"];
if (coCookie == null)
{
var Id= HttpContext.Current.User.Identity.Name.Int(); **//here i need to get the value but i am getting null value**
IdNmList cos = new EmployeeDAL().GetCompany(Id);
if (cos.Count == 0)
{
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary
{
{ "controller" , "Company"},
{ "action" , "Add"}
});
}
else if (cos.Count == 1)
{
filterContext.HttpContext.Response.Cookies.Add(new HttpCookie("CoId", cos[0].Id.ToString()));
}
else
{
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary
{
{ "controller", "Company" },
{ "action", "Select" },
{ "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
});
}
}
base.OnActionExecuting(filterContext);
}
}

Resources