public async Task <IActionResult> Edit(long id, IFormFile imageUrl, StudentCreateViewModel model, [Bind("ID,studentID,firstName,lastName,enrollmentDate,acquiredCredits,currentSemestar,educationLevel,profilePicture")] Student student) { if (id != student.ID) { return(NotFound()); } StudentsController uploadImage = new StudentsController(_context, webHostingEnvironment); student.profilePicture = uploadImage.UploadedFile(imageUrl); if (ModelState.IsValid) { try { _context.Update(student); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!StudentExists(student.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Details", new { id = student.ID })); } return(View(student)); }
public ActionResult Create(StudentCreateViewModel viewModel) { try { var newStudent = viewModel.Student; using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @" INSERT INTO Student (FirstName, LastName, SlackHandle, CohortId) VALUES (@firstName, @lastName, @slackHandle, @cohortId);"; cmd.Parameters.Add(new SqlParameter("@firstName", newStudent.FirstName)); cmd.Parameters.Add(new SqlParameter("@lastName", newStudent.LastName)); cmd.Parameters.Add(new SqlParameter("@slackHandle", newStudent.SlackHandle)); cmd.Parameters.Add(new SqlParameter("@cohortId", newStudent.CohortId)); cmd.ExecuteNonQuery(); } } return(RedirectToAction(nameof(Index))); } catch { return(View()); } }
public IActionResult Create(StudentCreateViewModel model) { if (ModelState.IsValid) { string uniqueFileName = null; if (model.Photo != null) { uniqueFileName = ProcessUpload(model.Photo); } var student = new Student { Name = model.Name, Email = model.Email, ClassName = model.ClassName, PhotoPath = uniqueFileName, }; // 处理多文件上传 if (model.Gallery != null && model.Gallery.Count > 0) { foreach (var photo in model.Gallery) { ProcessUpload(photo); } } var newStudent = _studentRepository.Add(student); return(RedirectToAction("details", new { id = newStudent.Id })); } return(View()); }
public IActionResult Create(StudentCreateViewModel model) { if (ModelState.IsValid) { string uniqueFileName = null; if (model.Photos != null && model.Photos.Count() > 0) { foreach (IFormFile photo in model.Photos) { //必须将图片文件上传到wwwroot的images/avatars文件夹中而要获取wwwroot文件夹的 //路径,我们需要注入ASP.NET Core提供的WebHost Environment 服务通过 //WebHostEnvironment服务获取wwwroot文件夹的路径 string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "avatars"); //为了确保文件名是唯一的,我们在文件名后附加一个新的GUID值和一个下划线 uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); //使用IFormFile接口提供的CopyTo()方法将文件复制到wwwroot/images/avatars文件夹 photo.CopyTo(new FileStream(filePath, FileMode.Create)); } } Student newStudent = new Student { Name = model.Name, Email = model.Email, Major = model.Major, ClassName = model.ClassName, // 将文件名保存在Student对象的PhotoPath属性中 //它将被保存到数据库Students的表中 PhotoPath = uniqueFileName, }; _studentRepository.AddStudent(newStudent); return(RedirectToAction("Detail", new { id = newStudent.Id })); } return(View()); }
public IActionResult Create(StudentCreateViewModel studentViewModel) { if (ModelState.IsValid) { string uniqueFileName; StudentModel student = studentViewModel.Student; if (studentViewModel.Photo != null) { //指定上传的文件储存在wwwroot/images文件夹中 string uploadFolder = Path.Combine(_hostEnvironment.WebRootPath, "images"); //为上传的文件添加GUID文件名 uniqueFileName = Guid.NewGuid().ToString() + "_" + studentViewModel.Photo.FileName; string filePath = Path.Combine(uploadFolder, uniqueFileName); //把上传的文件从内存中拷贝到硬盘上 studentViewModel.Photo.CopyToAsync(new FileStream(filePath, FileMode.Create)); student.PhotoPath = uniqueFileName; } else { //如果用户没有上传图片,则使用默认图片。 student.PhotoPath = "default.jpg"; } //把新创建的student提交到数据库 _studentService.Add(student); //完成后,返回到详情页面 return(RedirectToAction("Details", new { id = studentViewModel.Student.Id })); } //如果没有通过模型校验,返回Create()操作方法。 return(View()); }
// GET: Students/Create public ActionResult Create() { StudentCreateViewModel viewModel = new StudentCreateViewModel(); return(View()); }
public IActionResult Create(StudentCreateViewModel model) { if (ModelState.IsValid) { Student newStudent = new Student { StudentName = model.StudentName, }; DbContext.Students.Add(newStudent); DbContext.SaveChanges(); foreach (var selectedCourse in model.SelectedCourse.Where(s => s.isSelect)) { var courseStudent = new StudentCourse() { CourseId = selectedCourse.CourseId, StudentId = newStudent.StudentId }; DbContext.studentCourses.Add(courseStudent); DbContext.SaveChanges(); } return(RedirectToAction("Index")); } return(View(model)); }
public ActionResult Create(int?id) { if (id == null) { var allCourses = db.Courses.ToList(); var viewModel = new StudentCreateViewModel { Courses = allCourses, CourseSelected = false }; return(View(viewModel)); } var course = db.Courses.Find(id); if (course == null) { return(RedirectToAction("Index", "Home")); } var viewModelSelectedCourse = new StudentCreateViewModel { AttendingCourse = course.FullCourseName, CourseId = course.Id, CourseSelected = true }; return(View(viewModelSelectedCourse)); }
public ActionResult Create(StudentCreateViewModel viewModel) { try { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"INSERT INTO students (First_Name, Last_Name, Slack_Handle, Cohort_id) VALUES (@First_Name, @Last_Name, @Slack_Handle, @Cohort_id)"; cmd.Parameters.Add(new SqlParameter("@First_Name", viewModel.Student.FirstName)); cmd.Parameters.Add(new SqlParameter("@Last_Name", viewModel.Student.LastName)); cmd.Parameters.Add(new SqlParameter("@Slack_Handle", viewModel.Student.SlackHandle)); cmd.Parameters.Add(new SqlParameter("@Cohort_id", viewModel.Student.CohortId)); cmd.ExecuteNonQuery(); return(RedirectToAction(nameof(Index))); } } } catch { return(View()); } }
// GET: Students/Create public ActionResult Create() { var viewModel = new StudentCreateViewModel(); viewModel.Cohorts = cohortList(); return(View(viewModel)); }
//提炼共享的私有方法,处理文件信息 /// <summary> /// 将图片保存指定的路径中,并返回唯一的文件名 /// </summary> /// <returns></returns> private string ProcessUploadedFile(StudentCreateViewModel model) { string uniqueFileName = null; if (model.Photos != null && model.Photos.Count > 0) { foreach (var Photo in model.Photos) { //必须将图像上传到WWWroot中的images文件夹 //而要获取wwwroot文件夹的路径,我们需要注入ASP.NET Core提供的HostingEnvironment服务 string uploadFolder = Path.Combine(hostingEnvironment.WebRootPath, "images"); //为了确保文件名是唯一的,我们在文件名后附加一个新的GUID值和一个下划线 uniqueFileName = Guid.NewGuid().ToString() + "_" + Photo.FileName;//添加全局唯一标识符 string filePath2 = Path.Combine(uploadFolder, uniqueFileName); //使用IFormFile接口提供的CopyTo()方法将文件复制到wwwroot/images文件夹 //因为使用的非托管资源,所以需要手动释放.非托管资源垃圾回收器无法自动释放. using (var fileStrem = new FileStream(filePath2, FileMode.Create)) { //这里使用 Photo.CopyTo(fileStrem); //这里释放 } //Photo.CopyTo(new FileStream(filePath2, FileMode.Create));//流处理FileMode继承与IDisposable } } return(uniqueFileName); }
public async Task <IActionResult> Edit(int id, [Bind("Student,CourseID")] StudentCreateViewModel studentCreateViewModel) { if (id != studentCreateViewModel.Student.Id) { return(NotFound()); } if (ModelState.IsValid) { try { var student = studentCreateViewModel.Student; student.Course = db.Courses.Find(studentCreateViewModel.CourseID); db.Update(student); await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!StudentExists(studentCreateViewModel.Student.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(studentCreateViewModel)); }
// GET: Student/Edit/5 public ActionResult Edit(int id) { using (SqlConnection conn = Connection) { var viewModel = new StudentCreateViewModel(); var cohorts = GetAllCohorts(); var student = GetStudent(id); var selectItems = cohorts .Select(cohort => new SelectListItem { Text = cohort.Name, Value = cohort.Id.ToString() }) .ToList(); selectItems.Insert(0, new SelectListItem { Text = "Choose cohort...", Value = "0" }); viewModel.Cohorts = selectItems; viewModel.Student = student; return(View(viewModel)); } }
public async Task <IActionResult> Create(StudentCreateViewModel model) { if (ModelState.IsValid) { string uniqueFileName = UploadedFile(model); Student student = new Student { ID = model.ID, studentID = model.studentID, firstName = model.firstName, lastName = model.lastName, enrollmentDate = model.enrollmentDate, acquiredCredits = model.acquiredCredits, currentSemestar = model.currentSemestar, educationLevel = model.educationLevel, profilePicture = uniqueFileName }; _context.Add(student); await _context.SaveChangesAsync(); return(RedirectToAction("Details", new { ID = student.ID })); } return(View()); }
public IActionResult Create(StudentCreateViewModel model) { if (ModelState.IsValid) { //封装好了的上传图片代码 var uniqueFileName = ProcessUploadedFile(model); Student newStudent = new Student { Name = model.Name, Email = model.Email, Major = model.Major, EnrollmentDate = model.EnrollmentDate, // 将文件名保存在student对象的PhotoPath属性中。 //它将保存到数据库 Students的 表中 PhotoPath = uniqueFileName }; _studentRepository.Insert(newStudent); var encryptedId = _protector.Protect(newStudent.Id.ToString()); return(RedirectToAction("Details", new { id = encryptedId })); } return(View()); }
public ActionResult Create([FromForm] StudentCreateViewModel model) { try { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"INSERT INTO Student (FirstName, LastName, SlackHandle, CohortId) OUTPUT INSERTED.Id VALUES (@firstName, @lastName, @handle, @cId)"; cmd.Parameters.Add(new SqlParameter("@firstName", model.Student.FirstName)); cmd.Parameters.Add(new SqlParameter("@lastName", model.Student.LastName)); cmd.Parameters.Add(new SqlParameter("@handle", model.Student.SlackHandle)); cmd.Parameters.Add(new SqlParameter("@cId", model.Student.CohortId)); int newId = (int)cmd.ExecuteScalar(); return(RedirectToAction(nameof(Index))); } } } catch { return(View()); } }
private void btnCreate_Click(object sender, EventArgs e) { bool result = false; var message = ValidateFunction(ref result); if (result) { var studentUser = new StudentCreateViewModel() { Address = txtAddress.Text, Email = txtEmail.Text, Name = txtName.Text, Password = txtPassword.Text, Username = txtUsername.Text }; var studentCreateResult = UserService.CreateStudentUser(studentUser); if (studentCreateResult.Status) { ResetTextFields(); LoadData(); } else { MessageBox.Show(studentCreateResult.Message, "Error!"); } } else { MessageBox.Show(message); } }
public IActionResult Create(StudentCreateViewModel model) { if (ModelState.IsValid) { string uniqueFileName = null; if (model.Photo != null) { //必须将图像上传到wwwroot中的images文件夹 //而要获取wwwroot文件夹的路径,我们需要注入 ASP.NET Core提供的HostingEnvironment服务 string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images"); //为了确保文件名是唯一的,我们在文件名后附加一个新的GUID值和一个下划线 uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); //使用IFormFile接口提供的CopyTo()方法将文件复制到wwwroot/images文件夹 model.Photo.CopyTo(new FileStream(filePath, FileMode.Create)); } Student newStudent = new Student { Name = model.Name, Email = model.Email, ClassName = model.ClassName, // 将文件名保存在student对象的PhotoPath属性中 它将保存到数据库 Students的 表中 PhotoPath = uniqueFileName }; _studentRepository.Add(newStudent); return(RedirectToAction("details", new { id = newStudent.Id })); } return(View()); }
public IActionResult Create(StudentCreateViewModel model) { if (ModelState.IsValid) { string filename = null; if (model.PhotoPath != null) { string uploads = Path.Combine( histingEnviroment.WebRootPath, "images" ); filename = Guid.NewGuid().ToString() + "_" + model.PhotoPath.FileName.ToString(); string filePath = Path.Combine(uploads, filename); model.PhotoPath.CopyTo(new FileStream(filePath, FileMode.Create)); } Student stud = new Student() { FullName = model.FullName, Address = model.Address, Division = model.Division, PhotoPath = filename }; var st = _repository.AddStudent(stud); // return RedirectToAction("Details", new {id = st.StudentId}); return(RedirectToAction("Details", new { id = stud.StudentId })); } return(View("Create")); }
public IActionResult Create(StudentCreateViewModel model) { if (ModelState.IsValid) { var uniqueFileName = string.Empty; if (model.Photos != null && model.Photos.Count > 0) { foreach (var photo in model.Photos) { uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName; var uploadFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images", "avatars"); string filePath = Path.Combine(uploadFolder, uniqueFileName); photo.CopyTo(new FileStream(filePath, FileMode.Create)); } } var student = new Student { Name = model.Name, Email = model.Email, Major = model.Major, PhotoPath = uniqueFileName, EnrollmentDate = model.EnrollmentDate }; Student newStudent = _studentRepository.Insert(student); var encryptedId = _dataProtector.Protect(newStudent.Id.ToString()); return(RedirectToAction("Details", new { id = encryptedId })); } return(View()); }
/// <summary> /// 将照片保存到指定的路径中,并返回唯一的文件名 /// </summary> /// <returns></returns> private string ProcessUploadedFile(StudentCreateViewModel model) { string uniqueFileName = null; if (model.Photos.Count > 0) { foreach (var photo in model.Photos) { //必须将图像上传到wwwroot中的images文件夹 //而要获取wwwroot文件夹的路径,我们需要注入 ASP.NET Core提供的HostingEnvironment服务 //通过HostingEnvironment服务去获取wwwroot文件夹的路径 string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images"); //为了确保文件名是唯一的,我们在文件名后附加一个新的GUID值和一个下划线 uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); //因为使用了非托管资源,所以需要手动进行释放 using (var fileStream = new FileStream(filePath, FileMode.Create)) { //使用IFormFile接口提供的CopyTo()方法将文件复制到wwwroot/images文件夹 photo.CopyTo(fileStream); } } } return(uniqueFileName); }
public ActionResult Edit(int id, StudentCreateViewModel viewModel) { try { var updatedStudent = viewModel.Student; using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"UPDATE Students SET FirstName = @firstname, LastName = @lastname, SlackHandle = @slackhandle, CohortId = @cohortId WHERE Id = @id"; cmd.Parameters.Add(new SqlParameter("@firstname", updatedStudent.FirstName)); cmd.Parameters.Add(new SqlParameter("@lastname", updatedStudent.LastName)); cmd.Parameters.Add(new SqlParameter("@slackhandle", updatedStudent.SlackHandle)); cmd.Parameters.Add(new SqlParameter("@cohortId", updatedStudent.CohortId)); cmd.Parameters.Add(new SqlParameter("@id", id)); cmd.ExecuteNonQuery(); } } return(RedirectToAction(nameof(Index))); } catch { return(View()); } }
public IActionResult Create(StudentCreateViewModel model) { if (ModelState.IsValid) { string uniqueFileName = null; if (model.Photos != null && model.Photos.Count > 0) { foreach (IFormFile photo in model.Photos) { // 要將圖片上傳至 wwwroot 的 images 底下 // 要取得 wwwroot 資料夾的路徑, 需要注入 ASP NET Core 提供的 WebHostEnvironment 服務 string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images"); uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); // 使用 IFormFile 提供的 CopyTo method 將檔案複製到 wwwroot/images // 這邊 wwwroot 底下如果沒有 images 會發出找不到路徑的錯 photo.CopyTo(new FileStream(filePath, FileMode.Create)); } } Student newStudent = new Student { Name = model.Name, Email = model.Email, Major = model.Major, PhotoPath = uniqueFileName }; _studentRepository.Insert(newStudent); return(RedirectToAction("Details", new { id = newStudent.Id })); } return(View()); }
public IActionResult Create(StudentCreateViewModel student) { if (ModelState.IsValid) //判断验证是否通过 { var newStudent = new Student { FirstName = student.FirstName, LastName = student.LastName, BirthDate = student.BirthDate, Gender = student.Gender }; var newmodel = _repsoitory.ADD(newStudent); //这样写刷新的时候会提交数据 //return View("Detail",newmodel); //重定向的写法 // return RedirectToAction("create","home"); //这样写有利于重构 return(RedirectToAction(nameof(Detail), new { id = newmodel.id })); } else { return(View()); } }
public ActionResult Create() { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"SELECT Id, Name FROM Cohort"; var reader = cmd.ExecuteReader(); var cohorts = new List <Cohort>(); while (reader.Read()) { cohorts.Add( new Cohort() { Id = reader.GetInt32(reader.GetOrdinal("Id")), Name = reader.GetString(reader.GetOrdinal("Name")), } ); } reader.Close(); var viewModel = new StudentCreateViewModel() { Cohorts = cohorts }; return(View(viewModel)); } } }
// GET: Students/Create public ActionResult Create() { StudentCreateViewModel viewModel = new StudentCreateViewModel(_configuration.GetConnectionString("DefaultConnection")); return(View(viewModel)); }
public async Task <ActionResult> Create(StudentCreateViewModel model) { try { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"INSERT INTO students ( first_name, last_name, slack_handle, cohort_id ) VALUES ( @first_name, @last_name, @slack_handle, @cohort_id )"; cmd.Parameters.Add(new SqlParameter("@first_name", model.Student.FirstName)); cmd.Parameters.Add(new SqlParameter("@last_name", model.Student.LastName)); cmd.Parameters.Add(new SqlParameter("@slack_handle", model.Student.SlackHandle)); cmd.Parameters.Add(new SqlParameter("@cohort_id", model.Student.CohortId)); await cmd.ExecuteNonQueryAsync(); return(RedirectToAction(nameof(Index))); } } } catch { return(View()); } }
public ActionResult Create(StudentCreateViewModel viewModel) { try { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"INSERT INTO student (firstname, lastname, slackhandle, cohortid) VALUES (@firstname, @lastname, @slackhandle, @cohortid)" ; cmd.Parameters.Add(new SqlParameter("@firstname", viewModel.Student.FirstName)); cmd.Parameters.Add(new SqlParameter("@lastname", viewModel.Student.LastName)); cmd.Parameters.Add(new SqlParameter("@slackhandle", viewModel.Student.SlackHandle)); cmd.Parameters.Add(new SqlParameter("@cohortid", viewModel.Student.CohortId)); cmd.ExecuteNonQuery(); return(RedirectToAction(nameof(Index))); } } } catch { viewModel.Cohorts = GetAllCohorts(); return(View(viewModel)); }; }
[ValidateAntiForgeryToken] // 针对post表单提交要加上这个注解,因为前端会放置一个隐藏域,表单提交的时候会把隐藏域提交,防止跨站请求伪造 public IActionResult Create(StudentCreateViewModel student) { // 如果StudentCreateViewModel中添加注解的属性字段通过了验证的话 if (ModelState.IsValid) { var newStudent = new Student { FirstName = student.FirstName, LastName = student.LastName, BrithDate = student.BrithDate, Gender = student.Gender }; var newModel = _repository.Add(newStudent); // 将student对象序列化为json字符串返回到前端 // return this.Content(JsonConvert.SerializeObject(student)); // 将添加成功的对象在Detail视图页面进行展示 // return View("Detail", newModel); /** * nameof(Detail)就相当于 "Detail"字符串,使用nameof的话,有利于重构 * 因为Detail方法需要一个参数,所以我们通过匿名类的方式传递参数id * * 之所以不使用 View("Detail", newModel);的方式 * 而使用RedirectToAction(nameof(Detail), new { id = newModel.Id})的方式 * 是想等到student对象添加成功之后进行重定向改变浏览器的url,防止浏览器刷新造成多次表单提交 * **/ return(RedirectToAction(nameof(Detail), new { id = newModel.Id })); } // 如果没有通过验证还是显示原来的视图 return(View()); }
private string ProcessUploadFile(StudentCreateViewModel stu) { string uniquePhoto = null; /* Multiple file upload And In modelcreate view Class List<IFormFile> must be generic * if(stu.Photo!=null && stu.Photo.Count>0){ * foreach (IFormFile photo in stu.Photo) * { * string uploadsFolder = Path.Combine(_iWebHosting.WebRootPath, "images"); * uniquePhoto = Guid.NewGuid().ToString() + "_" + photo.FileName; * string filePath = Path.Combine(uploadsFolder, uniquePhoto); * photo.CopyTo(new FileStream(filePath, FileMode.Create)); * } * * }*/ //For single file upload if (stu.Photo != null) { string uploadsFolder = Path.Combine(_iWebHosting.WebRootPath, "images"); uniquePhoto = Guid.NewGuid().ToString() + "_" + stu.Photo.FileName; string filePath = Path.Combine(uploadsFolder, uniquePhoto); stu.Photo.CopyTo(new FileStream(filePath, FileMode.Create)); } return(uniquePhoto); }