Reputation: 115
Sorry if I didn't wrote my problem correctly, but I'll try to describe my situation in more detail. I'm developing application for storage text files. The idea of this app is: user create account(registration view), log in (login view) and after this user can view all text files that my local database (managing in sql server) has in WebGrid view. The problem is to transfer UserID value from Login View to UploadFile function in WorkSpaceController. I used RedirectToAction from "public ActionResult Login(UserDataClass log)" to transfer logged user email in FileManager function (that displays WebGridView). Function gets this useremail value and use it for getting UserID via SqlConnection for finally getting all files that user has by finishing query "select from UserData inner join FileData". The foreign key for FileData is "UserID" so I use it for uploading files to a current logged user to my database. And finally the problem is to transfer "useremail" value from "Login func" or from "FileManager" to a UploadFile to getting id again and getting an opportunity to upload files to dbo.FileData for a current user.
Hope you can help me to resolve this problem? I don't use Entity Framework for this manipulations because of situation.
If I described details incorrectly, I write more details if it needs.
UserDataController
public class UserDataController : Controller
{
string constr = ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString;
// GET: UserData
[HttpGet]
public ActionResult Login()
{
return View();
}
public ActionResult Registration()
{
return View();
}
[HttpPost]
public ActionResult Registration(UserDataClass reg) //Создание аккаунта
{
string connection = "Data Source=DESKTOP-LRLFA5K\\SQLEXPRESS;Initial Catalog=FileCloud;Integrated Security=True";
using (SqlConnection sqlcon = new SqlConnection(connection))
{
string sqlquery = "insert into UserData(UserName, UserEmail, UserPassword) values('" + reg.UserName + "','" + reg.UserEmail + "','" + reg.UserPassword + "')";
using (SqlCommand sqlcom = new SqlCommand(sqlquery, sqlcon))
{
sqlcon.Open();
sqlcom.ExecuteNonQuery();
sqlcon.Close();
}
}
return View(reg);
}
[HttpPost]
public ActionResult Login(UserDataClass log) //Авторизация
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-LRLFA5K\\SQLEXPRESS;Initial Catalog=FileCloud;Integrated Security=True;MultipleActiveResultSets=True";
SqlDataReader dr;
con.Open();
SqlCommand com = new SqlCommand("select * from UserData where UserEmail ='" + log.UserEmail + "' and UserPassword ='" + log.UserPassword + "'", con);
dr = com.ExecuteReader();
if (dr.Read())
{
Session["useremail"] = log.UserEmail.ToString();
return RedirectToAction("FileManager", "WorkSpace", new { useremail = log.UserEmail.ToString()});
}
else
{
ViewData["Message"] = "Неправильное имя пользователя или пароль";
}
con.Close();
return View();
}
WorkSpaceController
public class WorkSpaceController : Controller
{
string constr = ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString;
WorkSpaceClass ws = new WorkSpaceClass();
List<WorkSpaceClass> _ws = new List<WorkSpaceClass>();
// GET: WorkSpace
public ActionResult Add()
{
return View();
}
public ActionResult UploadFile(string useremail)
{
UserDataClass info = new UserDataClass();
info.UserEmail = Session["username"].ToString();
SqlConnection sqlcon = new SqlConnection(constr);
string comman = "select UserID from UserData where UserEmail = '" + info.UserEmail + "'"; //??? Вероятно, Email пуст...
using (SqlCommand sqlcom = new SqlCommand(comman, sqlcon))
{
sqlcon.Open();
TempData["UserID"] = sqlcom.ExecuteScalar();
}
//ws.UserID = id; //UserID не читается
sqlcon.Close();
return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase doc, string useremail) //Загружаем текстовый файл в БД
{
ViewBag.UserEmail = useremail;
if (doc != null)
{
ws.FileName = Path.GetFileName(doc.FileName);
ws.FileData = new byte[doc.ContentLength];
doc.InputStream.Read(ws.FileData, 0, doc.ContentLength);
ws.FileExtension = Path.GetExtension(ws.FileName);
DateTime FileDate = DateTime.Now;
SqlConnection sqlcon = new SqlConnection(constr);
ws.FileDate = FileDate.ToString("dd/MM/yyyy");
if (ws.FileExtension == ".doc" || ws.FileExtension == ".docx" || ws.FileExtension == ".txt" || ws.FileExtension == ".pdf")
{
string FilePath = Path.Combine(Server.MapPath("~/FileData"), ws.FileName); //Указываем дирректорию хранения файла
doc.SaveAs(FilePath);
string command = "insert into FileData(FileName, FileData, FileExtension, FileDate, UserID) values(@FileName, @FileData, @FileExtension, @FileDate, @UserID)";
sqlcon.Open();
SqlCommand sqlcom = new SqlCommand(command, sqlcon);
sqlcom.Parameters.Add("@FileName", SqlDbType.VarChar).Value = ws.FileName;
sqlcom.Parameters.Add("@FileData", SqlDbType.VarBinary).Value = ws.FileData;
sqlcom.Parameters.Add("@FileExtension", SqlDbType.VarChar).Value = ws.FileExtension;
sqlcom.Parameters.Add("@FileDate", SqlDbType.VarChar).Value = ws.FileDate;
sqlcom.Parameters.Add("@UserID", SqlDbType.Int).Value = (int)TempData["UserID"];
sqlcom.ExecuteNonQuery();
sqlcon.Close();
}
}
return View(ws);
}
public ActionResult FileManager(WorkSpaceClass wsc, string useremail)
{
UserDataClass info = new UserDataClass();
info.UserEmail = useremail;
SqlConnection sqlcon = new SqlConnection(constr);
string comman = "select UserID from UserData where UserEmail = '" + info.UserEmail + "'"; //??? Вероятно, Email пуст...
using (SqlCommand sqlcom = new SqlCommand(comman, sqlcon))
{
sqlcon.Open();
TempData["UserID"] = sqlcom.ExecuteScalar();
}
sqlcon.Close();
List<WorkSpaceClass> list = new List<WorkSpaceClass>();
DataTable dtFiles = GetFileDetails();
foreach (DataRow dr in dtFiles.Rows)
{
list.Add(new WorkSpaceClass
{
FileName = @dr["filename"].ToString(),
FileExtension = @dr["fileextension"].ToString(),
FileDate = @dr["filedate"].ToString(),
FileURL = dr["fileurl"].ToString()
}); ;
}
wsc.FileList = list;
return View(wsc);
}
private DataTable GetFileDetails()
{
DataTable dtData = new DataTable();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand command = new SqlCommand("select FileData.FileName, FileExtension, FileData, FileDate from UserData inner join FileData on FileData.UserID = UserData.UserID where UserData.UserID = '" + (int)TempData["UserID"] + "'", con);
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dtData);
con.Close();
return dtData;
}
public ActionResult DownloadFile(string FilePath)
{
string FileName = Server.MapPath("~" + FilePath);
byte[] FileData = GetFile(FileName);
return File(FileData, System.Net.Mime.MediaTypeNames.Application.Octet, FilePath);
}
byte[] GetFile(string s)
{
System.IO.FileStream fs = System.IO.File.OpenRead(s);
byte[] data = new byte[fs.Length];
int br = fs.Read(data, 0, data.Length);
if (br != fs.Length)
{
throw new System.IO.IOException(s);
}
return data;
}
UserDataClass Model
public class UserDataClass
{
public int UserID { get; set; }
[Display(Name = "Имя")]
[Required(ErrorMessage = "Введите имя пользователя")]
public string UserName { get; set; }
[Display(Name = "Email")]
[Required(ErrorMessage = "Введите Email")]
public string UserEmail { get; set; }
[Display(Name = "Пароль")]
[Required(ErrorMessage = "Введите пароль")]
public string UserPassword { get; set; }
[Display(Name = "Подтверждение пароля")]
[Required(ErrorMessage = "Подтвердите пароль")]
public string ConfirmPassword { get; set; }
[Display(Name = "Выберите изображение")]
public byte[] AvatarData { get; set; }
public HttpPostedFileBase ImageFile { get; set; } //??? Может это лишнее
}
WorkSpaceClass Model
public class WorkSpaceClass
{
public string FileName { get; set; }
public byte[] FileData { get; set; }
public string FileExtension { get; set; }
public string FileDate { get; set; }
public int UserID { get; set; }
public string FileURL { get; set; }
public IEnumerable<WorkSpaceClass> FileList { get; set; }
}
Upvotes: 1
Views: 176
Reputation: 582
As per my understanding, Your FileManager
action take more than one argument
and you pass only one argument
from login
action method. your action method is
public ActionResult FileManager(WorkSpaceClass wsc, string useremail)
and you pass only useremail
not WorkSpaceClass
return RedirectToAction("FileManager", "WorkSpace", new { useremail = log.UserEmail.ToString()});
Resolution
So try to pass WorkSpaceClass
object also to the FileManager
action method from Login
Action method like this.
return RedirectToAction("FileManager", "WorkSpace", new { wsc=new WorkSpaceClass(), useremail = log.UserEmail.ToString()});
Upvotes: 0