Reputation: 516
I'm trying to receive a file from vie, by using simple form here it is what I've tried
VIEW
@{
ViewBag.Title = "_CreateStudent";
}
<div class="CreatePartial">
<h2 class="blue-color">Create Student</h2>
<form method="POST" action="@Url.Action("Create","Student")" enctype="multipart/form-data">
<div>
<label for="Key">Student ID</label>
<input type="text" name="StudentID" hidden id="Key" />
</div>
<div>
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName" />
</div>
<div>
<label for="LastName">Last Name</label>
<input type="text" name="LastName" id="LastName" />
</div>
<div>
<label for="Photo">Profile Picture</label>
<input type="file" name="PhotoURL" id="photo" />
</div>
<input type="submit"/>
</form>
CONTROLLER
//CREATE STUDENTS POST
[HttpPost]
public ActionResult Create(StudentModel student, HttpPostedFileBase file)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName);
}
var StudentData = new Student()
{
StudentID = student.StudentID,
FirstName = student.FirstName,
LastName = student.LastName,
PhotoURL = file.FileName
};
db.Students.Add(StudentData);
db.SaveChanges();
return RedirectToAction("Index");
}
MODEL
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebApplication3.Models
{
public class StudentModel
{
[Required]
public int StudentID { get; set; }
[Required(ErrorMessage = "Please Enter FirstName to Proceed")]
public String FirstName { get; set; }
[Required(ErrorMessage = "Please Enter LastName to Proceed")]
public String LastName { get; set; }
[Required(ErrorMessage = "Please Select your Profile picture")]
public String PhotoURL { get; set; }
public List<StudentModel> _StudentList { get; set; }
}
}
but i'm getting HttpPostedFileBase
null
but the StudentModel
is received FirstName
,LastName
, PhotoURL
Upvotes: 1
Views: 132
Reputation: 12491
You post your input like this:
<input type="file" name="PhotoURL" id="photo" />
Controller doesn't map your file becouse input name attribute that doesn't correspond your model or controller.
If you set name attribute PhotoURL
you either should write your Controller signature like this:
public ActionResult Create(StudentModel student, HttpPostedFileBase PhotoURL)
Or extend your StudentModel
with HttpPostedFileBase
property:
public HttpPostedFileBase PhotoURL { get; set; }
Upvotes: 1