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中。 –