ModelState validation on RedirectToAction in MVC - asp.net-mvc

I want to implement ModelState.AddModelError on RedirectToAction in MVC. Currently, I am not getting error message. Can anyone please help me?
if(ModelState.IsValid)
{
var HList = hDetails.HTrackerList().Where(x => x.AccId == user.AccountID && x.UserId == user.Id).Select(y=>y.HorseId).ToList();
var datainList = HList.Contains(model.HorseId);
if(!datainList)
{
hDetails.InsertHorse(model);
}
else
{
ModelState.AddModelError("datainList", "Horse is already exist. Do you want to update it?");
}
}
return RedirectToAction("Home");
In the View:
#Html.ValidationMessage("datainList")

In your ontroller class:
public class YourController : Controller
{
[HttpPost]
public ActionResult TestMethod()
{
if(ModelState.IsValid)
{
var HList = hDetails.HTrackerList().Where(x => x.AccId == user.AccountID && x.UserId == user.Id).Select(y=>y.HorseId).ToList();
var datainList = HList.Contains(model.HorseId);
if(!datainList)
{
hDetails.InsertHorse(model);
}
else
{
TempData["datainListError"] = "Horse is already exist. Do you want to update it?";
}
}
return RedirectToAction("Home");
}
}
Then in the Home Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
if(TempData.ContainsKey("datainListError"))
{
ViewBag.ErrorMessage = TempData["datainListError"].ToString();
}
return View();
}
}
Then in the Index View:
#if(ViewBag.ErrorMessage != null)
{
<div class="alert alert-danger">#ViewBag.ErrorMessage</div>
}

Related

Can't get action result to run if statement and go to logged in section

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

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.)

How to stop code execute on condition from another controller?

my code:
public class StateManagementController : Controller
{
public void OwnerTest()
{
if (Session["Owner"] == null)
{
Logowanie();
}
}
public ActionResult Logowanie()
{
return RedirectToAction("Log", "Owner");
}
}
public class AnimalController : StateManagementController
{
public ActionResult MyAnimals()
{
OwnerTest();
//some code here
return View(animals.ToList());
}
}
The problem is that even if the session is null and Redirect is reached it doesn't redirect me but it still goes to ,,some code" in MyAnimals action, how can I stop it in ActionResult Logowanie? i dont want to change code in MyAnimals, I want only to use function there without checking if it returns something.
You Logowanie Action may return an ActionResult but the OwnerTest method ignores the returned result. Try this:
public class StateManagementController : Controller
{
public ActionResult OwnerTest()
{
if (Session["Owner"] == null)
{
return Logowanie();
}
else
{
return null;
}
}
public ActionResult Logowanie()
{
return RedirectToAction("Log", "Owner");
}
public class AnimalController : StateManagementController
{
public ActionResult MyAnimals()
{
var temp = OwnerTest();
if (temp != null)
{
return temp;
}
else
{
//some code here
return View(animals.ToList());
}
}
}

Issue with Request.IsAuthenticated after Login page mvc asp.net

I am having an issue with checking the authentication when a user logs in to my site. So I have a login page (Login.cshtml), that of course a user would login from. From there the user would be sent to an index page. My issue is that when i hit this
#if (Request.IsAuthenticated)
{
<strong>#Html.Encode(User.Identity.Name)</strong>
}
else
{
<strong>Something went wrong</strong>
}
it fails into the else statement and writes something went wrong. Any advice on how to combat this error would be greatly appreciated. Thank you in advance.
Index.cshtml:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#if (Request.IsAuthenticated)
{
<strong>#Html.Encode(User.Identity.Name)</strong>
}
else
{
<strong>Something went wrong</strong>
}
My UserContoller(has all the methods for the login):
public ActionResult Index()
{
var user = db.User.Include(u => u.UserName);
var loggedInUser = User.Identity.Name;
return View();
}
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(Models.User user)
{
if (ModelState.IsValid)
{
if (isValid(user.UserName, user.Password))
{
FormsAuthentication.SetAuthCookie(user.UserName, false);
return RedirectToAction("Index", "User");
}
else
{
ModelState.AddModelError("", "User Name or Password is incorrect");
}
}
return View(user);
}
private bool isValid(string UserName, string Password)
{
bool isValid = false;
//var user = db.User.SingleOrDefault(u => u.UserName == UserName);
var user = db.User.Where(u => u.UserName == UserName).FirstOrDefault();
var pass = db.User.Where(u => u.Password == Password).FirstOrDefault();
if (user != null && pass != null)
{
isValid = true;
}
return isValid;
}

Resources