I do not agree with the "impossible", designated as the correct answer. If someone is still looking for an opportunity, here is a job that worked for me. I am using MVC5. The idea is to use a session variable. I got an idea from ASP.Net Form .
My Model / ViewModel (only relevant properties):
public partial class emp_leaves { public string fileNameOrig { get; set; } public byte[] fileContent { get; set; } public HttpPostedFileBase uploadFile { get; set; } }
In my controller (HttpPost): // Check
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(emp_leaves emp_leaves) { if (emp_leaves.uploadFile != null && emp_leaves.uploadFile.ContentLength>0 && !string.IsNullOrEmpty(emp_leaves.uploadFile.FileName)) { emp_leaves.fileNameOrig = Path.GetFileName(emp_leaves.uploadFile.FileName); emp_leaves.fileContent = new byte[emp_leaves.uploadFile.ContentLength]; emp_leaves.uploadFile.InputStream.Read(emp_leaves.fileContent, 0, emp_leaves.uploadFile.ContentLength); Session["emp_leaves.uploadFile"] = emp_leaves.uploadFile;
Finally, in my edit view: here I am conditionally showing a file upload control.
< script type = "text/javascript" > $("#removefile").on("click", function(e) { if (!confirm('Delete File?')) { e.preventDefault(); return false; } $('#fileNameOrig').val('');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> @model PPMSWEB.Models.emp_leaves @{ HttpPostedFileBase uploadFileSession = Session["emp_leaves.uploadFile"] == null ? null : (HttpPostedFileBase)Session["emp_leaves.uploadFile"]; } @using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="row"> @*irrelevant content removed*@ <div id="downloadlrfdiv" @((!String.IsNullOrEmpty(Model.fileNameOrig) && (Model.uploadFile==n ull || uploadFileSession !=null)) ? "" : "style=display:none;")> <label>Attachment</label> <span> <strong> <a id="downloadlrf" href="@(uploadFileSession != null? "" : Url.Action("DownloadLRF", "emp_leaves", new { empLeaveId = Model.ID }))" class="text-primary ui-button-text-icon-primary" title="Download attached file"> @Model.fileNameOrig </a> </strong> @if (isEditable && !Model.readonlyMode) { @Html.Raw(" "); <a id="removefile" class="btn text-danger lead"> <strong title="Delete File" class="glyphicon glyphicon-minus-sign"> </strong> </a> } </span> </div> <div id="uploadlrfdiv" @(!(!String.IsNullOrEmpty(Model.fileNameOrig) && Model.uploadFile==n ull) && !Model.readonlyMode ? "" : "style=display:none;")> <label>Upload File</label> @Html.TextBoxFor(model => model.uploadFile, new { @type = "file", @class = "btn btn-default", @title = "Upload file (max 300 KB)" }) @Html.ValidationMessageFor(x => x.uploadFile) </div> </div> }
Arfath Oct 24 '17 at 13:23 2017-10-24 13:23
source share