Can't get action result to run if statement and go to logged in section - asp.net-mvc

For some reason, The users in db.users.Where()is not working like the rest of the users in the code. Need some assistance to make it get to the logged in stage.
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
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)
{
Session["UserID"] = obj.UserID.ToString();
Session["Username"] = obj.Username.ToString();
return RedirectToAction("LoggedIn");
}
}
}
return View(users);
}
public ActionResult LoggedIn()
{
if (Session["UserID"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}

Related

put operations CRUD on a single file in asp.net

**Hello
I am developing an application with ASP.NET API, i created the controller entity and the MVC controllers that my generated CRUD operations in the view as follows (see picture), each operation in a file how to put it all in a single file.
**
enter image description here
controller code:
// GET: /Clients/
public ActionResult Index()
{
return View(db.CLIENT.ToList());
}
// GET: /Clients/Details/5
public ActionResult Details(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Client_H Client_H = db.Client_H.Find(id);
if (Client_H == null)
{
return HttpNotFound();
}
return View(Client_H);
}
// GET: /Clients/Create
public ActionResult Create()
{
return View();
}
// POST: /Clients/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="ID,nom,prenom,CODE,ADRESSE,BQE_VILLE,ADRESSE,TEL")] Client_H Client_H)
{
if (ModelState.IsValid)
{
db.Client_H.Add(Client_H);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(Client_H);
}
// GET: /Clients/Edit/5
public ActionResult Edit(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Client_H Client_H = db.Client_H.Find(id);
if (Client_H == null)
{
return HttpNotFound();
}
return View(Client_H);
}
// POST: /Clients/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="ID,nom,prenom,CODE,ADRESSE,BQE_VILLE,ADRESSE,TEL")] Client_H Client_H)
{
if (ModelState.IsValid)
{
db.Entry(Client_H).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(Client_H);
}
// GET: /Clients/Delete/5
public ActionResult Delete(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Client_H Client_H = db.Client_H.Find(id);
if (Client_H == null)
{
return HttpNotFound();
}
return View(Client_H);
}
// POST: /Clients/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(long id)
{
Client_H Client_H = db.Client_H.Find(id);
db.Client_H.Remove(Client_H);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
Thank you in advance
I do not understand well what do you mean by "how to put it all in a single file"?
If you want to have all CRUD function in on 1 view, you can use jquery POST & GET.
https://api.jquery.com/jquery.post/
https://api.jquery.com/jquery.get/

Print Function using Rotativa

i used Rotativa to print one of my page from html to pdf and when i hit the button to print,it will open print preview,but the preview does not contains that page i just print , it contains and show me log in page in preview instead as you can see,so idont know exactly whats happend.Can someone please point me in the right direction?
The page i tried to print look like this:
But when i hit the button to print,in preview give me log in page:
AccountController:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Session["CustomerID"] == null &! Request.RawUrl.ToLower().Contains("login"))
{
Response.Redirect("/Account/Login");
}
base.OnActionExecuting(filterContext);
}
<br>
//Login
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(Customers cust)
{
using (DataContext db = new DataContext())
{
var user = db.Customers.Where(u => u.CustomerID == cust.CustomerID).FirstOrDefault();
if (user != null)
{
Session["CustomerID"] = user.CustomerID.ToString();
FormsAuthentication.SetAuthCookie(cust.CustomerID, false);
Session.Timeout = 30;
return RedirectToAction("LoggedIn");
}
else
{
ModelState.AddModelError("", "CustomerID is not Valid");
}
}
return View();
}
public ActionResult LoggedIn()
{
if (Session["CustomerID"] != null)
{
string customerId = Session["CustomerID"].ToString();
List<Orders> customerOrders;
using (DataContext data = new DataContext())
{
customerOrders = data.Orders.Where(x => x.CustomerID == customerId).ToList();
}
return View(customerOrders);
}
else
{
return RedirectToAction("Login");
}
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
Session.Remove("Login");
return RedirectToAction("Login", "Account");
}
public ActionResult PrintOrders(int id)
{
var report = new ActionAsPdf("ShowOrdersDetails", new { id = id });
return report;
}

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

CRUD in MVC repository

I have created a repository data layer in my MVC web application, and want to use it for my CRUD methods. But I came to think of situations where I want to do something like:
If record does not exist
create record
else
update record
But how does this fit into CRUD? Is this two-in-one operation logic supposed to be kept in the controller?
I think the repository should take care of that, the controller should be as light as possible:
At repository level:
public bool CreateUpdate(Type model)
{
var record = db.FirstOrDefault(x=> x.Id == model.Id);
if(record == null)
{
Create(model);
}
else
{
Update(model);
}
}
public bool Create(Type model)
{
//create logic here
}
public bool Update(Type model)
{
//update logic here
}
This can be done with this code
var data = db.tableName.where(x=> x.Id == model.Id).FirstOrDefault();
if(data== null)
{
db.FAQCategories.Add(model);
db.SaveChanges();
}
else
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
}
public IActionResult Create()
{
return View();
}
// POST: AdminPanel/Students/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Student student)
{
if (!ModelState.IsValid)
{
return View();
}
student.Image = await student.Photo.SaveFileAsync(_environment.WebRootPath, "images");
await _context.Students.AddAsync(student);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
// GET: AdminPanel/Students/Edit/5
public async Task<IActionResult> Update(int? id)
{
if (id == null)
{
return BadRequest();
}
var student = await _context.Students.FindAsync(id);
if (student == null)
{
return NotFound();
}
return View(student);
}
// POST: AdminPanel/Students/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Update(int? id, Student newstudent)
{
if (id==null)
{
return BadRequest();
}
var oldstudent = _context.Students.Find(id);
if (oldstudent == null)
{
return NotFound();
}
if (!ModelState.IsValid)
{
return View();
}
var path = Helper.GetPath(_environment.WebRootPath, "images", oldstudent.Image);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
newstudent.Image = await newstudent.Photo.SaveFileAsync(_env.WebRootPath, "images");
oldstudent.Image = newstudent.Image;
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Delete(int id)
{
if (id == null)
{
return BadRequest();
}
var student= _context.Students.Find(id);
if (student== null)
{
return NotFound();
}
_context.Students.Remove(student);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}

Resources