c# - 创建一个 ASP.net MVC Web 应用程序,详细信息如下:
问题描述
从用户获取图像并将用户表的图像保存在数据库中。添加视图以显示用户Images
列表视图中文件夹中的用户图像以及用户的其他信息。
现在这个问题的原因是,当我尝试将其保存在数据库中时,它成功地保存了图像,但没有保存在Images
文件夹中,我尝试了所有方法,但没有一种方法有效。
我的代码:
Employee
控制器:
using My_Work.DAL;
using My_Work.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using PagedList.Mvc;
using System.IO;
namespace My_Work.Controllers
{
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult Index(string SearchBy, string SearchTerm,
int? page, string sortBy)
{
//In case of Invalid user redirect to login
if (Session["login"] == null)
{
return RedirectToAction("Login", "User");
}
ViewBag.CitySort = String.IsNullOrEmpty(sortBy) ? "City desc" : "City";
ViewBag.GenderSort = sortBy == "Gender" ? "Gender desc" : "Gender";
EmployeeEntity entity = new EmployeeEntity();
List<Employee> list = entity.GetList(SearchBy,
SearchTerm, sortBy);
HttpCookie cookie = Request.Cookies["Detalis"];
if (cookie != null)
{
string color = cookie["Lastlogin"];
}
return View(list.ToPagedList(page ?? 1, 5));
}
public ActionResult Create()
{
//In case of Invalid user redirect to login
if (Session["login"] == null)
{
return RedirectToAction("Login", "User");
}
ViewBag.DepartmentsList = getDepartmentList();
//ViewBag.LanguagesList = GetLanguagesList();
return View();
}
[HttpPost]
public ActionResult Create(Employee employee)
{
if (Session["login"] == null)
{
return RedirectToAction("Login", "User");
}
if (ModelState.IsValid)
{
var allowedExtensions = new[] {".Jpg", ".png", ".jpg", "jpeg"};
var ext = Path.GetExtension(employee.file.FileName);
//getting the extension(ex-.jpg)
if (allowedExtensions.Contains(ext)) //check what type of extension
{
//~/Images is relative path for images in root directory
var path = Path.Combine(Server.MapPath("~/Images"),Path.GetFileName(employee.file.FileName));
employee.ImageURL = employee.file.FileName;
//saving photo of employee in the image folder
// file.SaveAs Saves the contents of an uploaded file to a specified path on the Web server.
employee.file.SaveAs(path);
}
else
{
ViewBag.message = "Please choose only Image file";
ViewBag.DepartmentsList = getDepartmentList();
return View(employee);
}
EmployeeEntity entity = new EmployeeEntity();
int count = entity.insert(employee);
if (count > 0)
{
ViewBag.successMessage = "Data insterted Successfully !";
}
ModelState.Clear();
}
ViewBag.DepartmentsList = getDepartmentList();
return View(employee);
}
[HttpPost]
public ActionResult Delete(long id)
{
//In case of Invalid user redirect to login
if (Session["login"] == null)
{
return RedirectToAction("Login", "User");
}
EmployeeEntity entity = new EmployeeEntity();
int RowCount = entity.DeleteEmployee(id);
return RedirectToAction("Index");
}
public ActionResult Edit(int id)
{
//In case of Invalid user redirect to login
if (Session["login"] == null)
{
return RedirectToAction("Login", "User");
}
Employee emp = new EmployeeEntity().GetSingleEmployee(id);
ViewBag.DepartmentsList = getDepartmentList();
return View(emp);
}
[HttpPost]
public ActionResult Edit(Employee employee)
{
//In case of Invalid user redirect to login
if (Session["login"] == null)
{
return RedirectToAction("Login", "User");
}
int RowCount = new
EmployeeEntity().UpdateEmployee(employee);
return RedirectToAction("Index");
}
private List<SelectListItem> getDepartmentList()
{
List<SelectListItem> departmentList = new
Department().getDepartmentList();
return departmentList;
}
}
}
Employee
模型:
using My_Work.CustomValidation;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace My_Work.Models
{
public class Employee
{
public int EmployeeID { get; set; }
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
[Required]
public string Gender { get; set; }
[Required]
[Range(20, 60, ErrorMessage = "Age must be between 20 and 60")]
[Display(Name = "Age")]
public int Age { get; set; }
[Required]
[Display(Name = "Education Level")]
public int EducationLevel { get; set; }
[Range(25000, 500000, ErrorMessage = "Please enter correct value")]
[Required]
/* We can control the display of data in a View (UI) using
display attributes */
[Display(Name = "Salary")]
public int Salary { get; set; }
[Required]
[EmailAddress]
public string EmailAddress { get; set; }
[Required(ErrorMessage = "Please enter hire date")]
[Display(Name = "Hire Date")]
[CustomHireDate(ErrorMessage = "Hire Date must be less than or equal to Today's Date")]
[DataType(DataType.Date)]
public DateTime? HireDate { get; set; }
public string City { get; set; }
public Department department { get; set; }
public string ImageURL { get; set; }
[Required]
[Display(Name = "Upload Photo")]
public HttpPostedFileBase file { get; set; }
}
}
EmployeeEntity
班级:
using My_Work.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Configuration;
namespace My_Work.DAL
{
public class EmployeeEntity
{
string ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection sqlConnection = null;
SqlCommand cmd = null;
public int insert(Employee employee)
{
int effectedRows = 0;
try
{
sqlConnection = new SqlConnection(ConnectionString);
string query = @"insert into Employee(EmployeeID,FirstName,LastName,Gender,Age,EducationLevel,Salary,EmailAddress,HireDate,
City,DepartmentID,ImageURL)
values('" + employee.EmployeeID + "','" + employee.FirstName + "','"
+ employee.LastName + "','" + employee.Gender + "','" + employee.Age +
"','" + employee.EducationLevel + "','" + employee.Salary + "','" +
employee.EmailAddress + "','" + employee.HireDate + "','" +
employee.City + "','" + employee.department.DepartmentID +
"','" + employee.ImageURL + "')";
sqlConnection.Open();
cmd = new SqlCommand(query, sqlConnection);
effectedRows = cmd.ExecuteNonQuery();
sqlConnection.Close();
return effectedRows;
}
catch (Exception exp)
{
return effectedRows;
}
}
public List<Employee> GetList(string searchBy, string search, string sortBy)
{
//Here we have passed searchBy and Search as parameters and we are
// going to apply where filter in SQL Query using these parameters
List<Employee> employeesList = new List<Employee>();
sqlConnection = new SqlConnection(ConnectionString);
string query = String.Empty;
if (String.IsNullOrEmpty(sortBy))
{
sortBy = "City";
}
if (!String.IsNullOrEmpty(searchBy))
{
query = @"select * from Employee inner join Department on Employee.DepartmentID = Department.DepartmentID where "
+ searchBy + " like '%" + search + "%'order by "+sortBy+"";
}
else
{
query = @"select * from Employee inner join Department on Employee.DepartmentID =
Department.DepartmentID order by " + sortBy + "";
}
cmd = new SqlCommand(query, sqlConnection);
sqlConnection.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
employeesList.Add(new Employee
{
EmployeeID = Convert.ToInt32(dataReader["EmployeeId"].ToString()),
FirstName = dataReader["FirstName"].ToString(),
LastName = dataReader["LastName"].ToString(),
Gender = dataReader["Gender"].ToString(),
City = dataReader["City"].ToString(),
EmailAddress = dataReader["EmailAddress"].ToString(),
Age = Convert.ToInt32(dataReader["Age"].ToString()),
Salary = Convert.ToInt32(dataReader["Salary"].ToString()),
EducationLevel = Convert.ToInt32(dataReader["EducationLevel"].ToString()),
HireDate = DateTime.Parse(dataReader["HireDate"].ToString()),
ImageURL = dataReader["ImageURL"].ToString(),
department = new Department
{
DepartmentID = Convert.ToInt32(dataReader["departmentId"].ToString()),
Name = dataReader["Name"].ToString()
}
});
}
sqlConnection.Close();
return employeesList;
}
public List<Employee> GetList()
{
List<Employee> EmployeeList = new List<Employee>();
sqlConnection = new SqlConnection(ConnectionString);
string query = @"select * from Employee emp inner join Department dept on emp.DepartmentID=dept.DepartmentID";
sqlConnection.Open();
cmd = new SqlCommand(query, sqlConnection);
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
EmployeeList.Add(new Employee
{
FirstName = dataReader["FirstName"].ToString(),
LastName = dataReader["LastName"].ToString(),
Gender = dataReader["Gender"].ToString(),
EmailAddress =
dataReader["EmailAddress"].ToString(),
City = dataReader["City"].ToString(),
Salary
= Convert.ToInt32(dataReader["Salary"].ToString()),
Age =
Convert.ToInt32(dataReader["Age"].ToString()),
EducationLevel =
Convert.ToInt32(dataReader["EducationLevel"].ToString()),
department = new Department
{
DepartmentID =
Convert.ToInt32(dataReader["DepartmentID"].ToString()),
Name = dataReader["Name"].ToString()
},
HireDate =
DateTime.Parse(dataReader["HireDate"].ToString())
});
}
sqlConnection.Close();
return EmployeeList;
}
}
}
Create
看法:
@model My_Work.Models.Employee
{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<title>Employee Information</title>
</head>
<body>
@using (Html.BeginForm("Create", "Employee", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
<div class="form-horizontal">
<h4 class="h1 text-center">Create Employee</h4>
<hr />
<div>
@if (ViewBag.successMessage != null)
{
<h3>@ViewBag.successMessage</h3>
}
</div>
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes:
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName,
"", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes:
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LastName,
"", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Gender, htmlAttributes: new
{ @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Gender, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Gender, "",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EmailAddress,
htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EmailAddress, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model =>
model.EmailAddress, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.City, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.City, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.City, "",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Salary, htmlAttributes: new
{ @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Salary, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Salary, "",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Age, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", new
{ @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EducationLevel,
htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EducationLevel, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model =>
model.EducationLevel, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.HireDate, htmlAttributes:
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.HireDate, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.HireDate,
"", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.department.DepartmentID,
htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model =>
model.department.DepartmentID,
(List<SelectListItem>)ViewBag.DepartmentsList)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.file, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.file, new { type = "file",
@class = "form-control" })
@Html.ValidationMessageFor(model => model.file, "",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btndefault" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to Main Page", "Index")
</div>
</body>
</html>
Index
看法:
@using PagedList.Mvc;
@using PagedList;
@model IPagedList<My_Work.Models.Employee>
@{
Layout = null;
HttpCookie cookie = Request.Cookies["Detalis"];
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div style="float:left">
@Html.ActionLink("Create New", "Create")
</div>
<div style="float:right">
@{
String img64 = (string)Session["userImage"];
String img64Url = string.Format("data:image/" +
(string)Session["userImageType"] + ";base64,{0}", img64);
//imagetype can be e.g. gif, jpeg, png etc.
}
<img alt="" src="@img64Url" width="40" height="40"
class="rounded-circle" />
<br />
@Html.ActionLink("Click to Logout", "Logout", "User")
</div>
<br />
<p>
@using (@Html.BeginForm("Customize", "Employee", FormMethod.Post))
{
<b>User Preferences:</b>
@Html.TextBox("RecordCount")
<input type="submit" value="Set Preferences" />
}
</p>
<p>
@using (@Html.BeginForm("Index", "Employee", FormMethod.Get))
{
<b>Search By:</b>
@Html.RadioButton("SearchBy", "City", true)
<text>City</text>
@Html.RadioButton("SearchBy", "Gender")
<text>Gender</text><br />
@Html.TextBox("search") <input type="submit"
value="search" />
}
</p>
<p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model =>
model.First().FirstName)
</th>
<th>
@Html.DisplayNameFor(model =>
model.First().EmailAddress)
</th>
<th>
@Html.ActionLink("Gender", "Index", new
{
sortBy = ViewBag.GenderSort,
SearchBy = Request["SearchBy"],
SearchTerm = Request["SearchTerm"]
})
</th>
<th>
@Html.ActionLink("City", "Index", new
{
sortBy = ViewBag.CitySort,
SearchBy = Request["SearchBy"],
SearchTerm = Request["SearchTerm"]
})
</th>
<th>
@Html.DisplayNameFor(model =>
model.First().HireDate)
</th>
<th>
Photo
</th>
</tr>
@if (Model.Count() == 0)
{
<tr>
<td colspan="6">
No records match search criteria
</td>
</tr>
}
else
{
foreach (var item in Model)
{
using (Html.BeginForm("Delete", "Employee", new
{
id = item.EmployeeID
}))
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmailAddress)
</td>
<td>
@Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.HireDate)
</td>
<td>
@if (!string.IsNullOrEmpty(item.ImageURL))
{
@*@Url.Content convert the relative path into application absolute
path*@
<img src="@Url.Content("~/Images/" + item.ImageURL)"
height="50px" width="50px" />
}
else
{
<span>No Image Found!</span>
}
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id =
item.EmployeeID }) |
@Html.ActionLink("Details", "Details", new { id =
item.EmployeeID }) |
<input type="submit" value="Delete" onclick="return confirm('do you really want to delete this record?');" />
</td>
</tr>
}
}
}
</table>
@Html.PagedListPager(Model, page => Url.Action("Index", new {
page, SearchBy = Request.QueryString["SearchBy"], SearchTerm =
Request.QueryString["SearchTerm"], sortBy =
Request.QueryString["sortBy"] }), new PagedListRenderOptions() {
Display = PagedListDisplayMode.IfNeeded,
DisplayPageCountAndCurrentLocation = true })
<br />
<div style="float:left">
<dl>
<dt>
@Html.ActionLink("User Last Login:", cookie["Lastlogin"])
</dt>
<dd>
@if (cookie != null)
{
@cookie["Lastlogin"];
}
</dd>
</dl>
</div>
<br />
</body>
</html>
Images
文件夹:
解决方案
推荐阅读
- wordpress - 账单地址作为新订单电子邮件 woocommerce 中的谷歌地图链接
- node.js - 在收到用户输入之前如何阻止?
- dart - 对于 "pubsub.stream.listen(print, onDone: (){print('done')}). " , "onDone:" 永远不会工作
- r - 时间序列月发生率
- mercurial - 如何从 hg repo 中删除变更集而不丢失之后提交的变更集
- javascript - 按字母顺序取消连续字符的资格。Sol [ASCII 格式]
- android - 识别内存泄漏
- scala - scala rdd flatmap 从一行生成多行以填充行间隙问题
- python - 知道图像中的单一 RGB 颜色,而不是 OpenCV 的范围
- javascript - 在反应中过滤数据?