如何在不同的模型中传递文件上传细节和其他输入
本文关键字:文件 输入 其他 细节 模型 | 更新日期: 2023-09-27 18:00:07
简历模型
public class Resume
{
public string Name { get; set; }
public byte[] Binary { get; set; }
public int PageCount { get; set; }
public string Path { get; set; }
}
接触式
public class Contact
{
public string Name { get; set; }
public string ContactNumber { get; set; }
public string Address{ get; set; }
}
学生模型
public class Student
{
public List<Contact> Contacts{ get; set; }
public List<Resumes> Resume{ get; set; }
}
这是View
@model SendAFaxWeb.Models.Student
@{
ViewBag.Title = "Upload";
}
@using (Html.BeginForm("Submit", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ @Html.AntiForgeryToken()
<div>
@Html.LabelFor(x => x.Contact.Name)
@Html.TextBoxFor(x => x.Contact.Name)
@Html.LabelFor(x => x.Contact.ContactNumber)
@Html.TextBoxFor(x => x.Contact.ContactNumber)
@Html.LabelFor(x => x.Contact.Address)
@Html.TextBoxFor(x => x.Contact.Address)
*//here should be upload resume, the detail will be save in Resumes model(name, binary, pageCount and path)*
@Html.Label("Upload Resume")
@Html.TextBoxFor(x => x.file, new { type = "file" })
</div>
<button type="submit">Upload</button>
}
控制器
public ActionResult Submit(Student stud)
{
//to save student details
}
抱歉我英语不好,我是MVC开发的新手。我的问题是,我不知道如何将文件和其他数据传递给控制器。控制器预期学生螺柱具有所有数据简历和联系。我该如何解决这个问题?
如果我认为您的代码是一种良好的实践:请尝试将其添加到您的Student类:
public HttpPostedFileBase FileToUpload { get; set;}
在视图中更改行:
@Html.TextBoxFor(x => x.FileToUpload, new { type = "file" })
然后在控制器中你可以这样做:
[HttpPost]
public ActionResult Index(Student model)
{
var file= model.FileToUpload;
if (file != null && file.ContentLength > 0)
{
// extract only the filename
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
但是,如果您考虑重新设计您的代码,这可能会使您获得更好的可管理性,请研究视图模型的概念。谷歌先生可以帮你很多忙。希望这能帮助