1
我有一个Razor页面,我加载一些数据(不是表单),其中一个“字段”是一个文件。从ViewBag加载文件?
<div class="col-sm-3">
<label>Upload Construction Map:</label>
<br />
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse @Html.TextBoxFor(m => m.ShapeFileModel.ConstructFile, new { id = "fu-construct", type = "file", accept = ".pdf" })
</span>
</span>
@{
if (fileId != "")
{
int theId = int.Parse(fileId);
CrossCData.DAL.File fileMap = (from f in dbCrossingsCloud.Files
where f.Id == theId
select f).SingleOrDefault();
<input type="text" id="txtPathConstruct" class="form-control" value="@fileMap.FileName" contenteditable="false" readonly />
}
else
{
<input type="text" id="txtPathConstruct" class="form-control" value="" contenteditable="false" readonly />
}
}
</div>
</div>
我返回ViewBag.fileId文件的ID,然后我得到存储在文件系统(不是数据库)的文件的细节。所以...文件位置(文件夹路径)和文件名。
是否可以在Razor中使用IO将文件加载到输入中?和一个JavaScript变量?
任何帮助将不胜感激!
的Javascript我用它来管理文件
$("#fu-construct").fileupload({
url: 'UploadConstructFile',
dataType: 'json',
// File was added
add: function (e, data) {
var fileExtension = ['pdf']; // Valid file extensions
if ($.inArray($("#txtPathConstruct").val().split('.').pop().toLowerCase(), fileExtension) == -1) {
swal("Error", "Only PDF files are allowed. Please select a file in PDF format.", "error");
$("#txtPathConstruct").val("No file chosen...");
constructData = null;
} else {
constructData = data;
}
},
// UploadConstructFile is done
done: function (event, data) {
fileId = data.result.fileId;
if (projectCompany == "" || typeof projectCompany == 'undefined') {
swal("Error", "Please enter a requesting company", "error");
}
else if (projectName == "" || typeof projectName == 'undefined') {
swal("Error", "Please enter a project name.", "error");
}
else if (projectType == "" || typeof projectType == 'undefined') {
swal("Error", "Please select a project type.", "error");
}
else {
post('Audit', 'post', JSON.stringify(myDataTable.rows().data().toArray()), fileId, projectCompany, projectName, projectType, projectFileNumber, projectAFECC);
}
},
fail: function (event, data) {
alert("Error uploading the file.");
$("#txtPathShape").val("No file chosen...");
}
});
$("#construct-upload").on('click', function() {
if (constructData) {
constructData.submit();
}
return false;
});
通常认为不好的做法是通过ViewBag传递数据。我建议使用强类型视图模型和HttpPostedFile类作为字段。 – JDupont
我重新阅读你的问题。您是否试图从服务器提供文件或让用户将文件上传到服务器?如果其后(*客户端发送文件到服务器*)我的答案不正确,但我可以用我的建议重写它。 – Igor
用户上载文件,一旦他们在Add.cshtml中提交,我将其保存到服务器,然后从Audit.cshtml文件中,用户想要回去修复信息,但我需要再次将文件加载到'constructData'在JavaScript中。 –