How to load second partialview after success inserted in first partialview? - asp.net-mvc

I have a view named Register.cshtml and 2 partialview named _AddUser.cshtml And _UserList.cshtml.
When I run the project shows register.cshtml and _AddUser.cshtml load in view. I want to load _UserList partialview after success inserted in _AddUser partialview.
DefaultController:
public class DefaultController : Controller
{
UserRepository UR = new UserRepository();
Automation_DBEntities database = new Automation_DBEntities();
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Users user, HttpPostedFileBase file)
{
UserRepository blUser = new UserRepository();
if (ModelState.IsValid)
{
///////////////////SaveImage
if (file != null)
{
if (user.UserImage != "no-photo.jpg")
{
if (System.IO.File.Exists(Server.MapPath("/image/UserImage/" + user.UserImage)))
System.IO.File.Delete(Server.MapPath("/image/UserImage/" + user.UserImage));
}
user.UserImage = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
file.SaveAs(Server.MapPath("/image/UserImage/" + user.UserImage));
}
user.RegisterDate = DateTime.Now;
if (blUser.Add(user))
{
return PartialView("_UserList");//Inserted
}
else
{
}
}
else
{
}
}
[HttpGet]
public ActionResult AddUser()
{
return PartialView("~/Areas/Admin/Views/Shared/_AddUser.cshtml");
}
[HttpGet]
public ActionResult UserList()
{
IQueryable<AutomationSystem.Models.DomainModel.Users> list = UR.Select();
return PartialView("~/Areas/Admin/Views/Shared/_UserList.cshtml", list);
}

Related

Return Action as result of another action?

public ActionResult Index(int requestid)
{
return View(db.RequestListDetails.Where(c=>c.RequestID == requestid).ToList());
}
How can I back to View(db.RequestListDetails.Where(c=>c.RequestID == requestid).ToList()); from Create action.
My Create action code like this
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "....")] RequestListDetail requestListDetail)
{
if (ModelState.IsValid)
{
db.RequestListDetails.Add(requestListDetail);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(requestListDetail);
}
After db.SaveChanges() you could use this:
return RedirectToAction("Index", new { requestid = requestListDetail.RequestId });

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

Uploading and Viewing Photos

Can anyone help i'm using MVC 5 and doing a code on uploading and displaying photos and i'm having an error (The name ' file ' does not exist in the current content) please help
This is the controller i'm using:
public class UploadController : Controller
{
private DataContext db = new DataContext();
public ActionResult Index()
{
var model = new UploadViewModel();
return View(model);
}
[HttpPost]
public ActionResult Upload(UploadViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
UploadDbModel fileUploadModel = new UploadDbModel();
try
{
if (file.ContentLength > 0)
{
byte[] uploadFile = new byte[model.File.InputStream.Length];
model.File.InputStream.Read(uploadFile, 0, uploadFile.Length);
fileUploadModel.FileName = model.File.FileName;
fileUploadModel.File = uploadFile;
db.UploadDbModels.Add(fileUploadModel);
db.SaveChanges();
}
return Content("FILE SUCCESSFULLY UPLOADED");
}
catch
{
return Content("UPLOAD FAILED");
}
}
public ActionResult Download()
{
return View(db.UploadDbModels.ToList());
}
public FileContentResult FileDownload(int? id)
{
byte[] fileData;
string fileName;
UploadDbModel fileRecord = db.UploadDbModels.Find(id);
fileData = (byte[])fileRecord.File.ToArray();
fileName = fileRecord.FileName;
return File(fileData, "text", fileName);
}
}
In Asp.Net MVC we have to use HttpPostedFileBase for Uploaded files as shown below :-
[HttpPost]
public ActionResult Upload(UploadViewModel model, HttpPostedFileBase file)
{
if (file != null)
{
int byteCount = file.ContentLength; <---Your file Size or Length
.............
.............
}
}
Try and use system.web, just add the reference on the assembly hope it works.

Resources