我试图通过使用简单的表单从vie接收文件 这是我尝试过的事情
查看
@{
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; }
}
}
但我得到了HttpPostedFileBase
null
但已收到StudentModel
FirstName
,LastName
,PhotoURL
答案 0 :(得分:1)
您发布的输入如下:
<input type="file" name="PhotoURL" id="photo" />
Controller不会映射您的文件,因为输入名称属性与您的模型或控制器不对应。
如果设置名称属性PhotoURL
,您应该像这样编写Controller签名:
public ActionResult Create(StudentModel student, HttpPostedFileBase PhotoURL)
或者使用StudentModel
属性扩展您的HttpPostedFileBase
:
public HttpPostedFileBase PhotoURL { get; set; }