I am working on an ASP.NET MVC 4 application and there are many views where the user can upload a file which I save on the server using Ajax.
My View page is,
<div class="row">
<br />
<div class="col-md-4" >
@Html.TextBoxFor(m => m.fileUpload, new { @class = "form-control", style = "height:33px;", type = "file", accept = "image/*,application/pdf" }).DisableIf(() => Model.IsReadOnly == true)
</div>
@if (Model.Status != Intranet.Common.Constants.Status.View)
{
<div class="form-group">
<button id="btnSubmitUpload" name="Command" value="Save"
class="btn btn-default">
Upload
</button>
</div>
}
</div>
<script type="text/javascript">
var model = @Html.Raw(Json.Encode(Model))
$(document).ready(function () {
$("#btnSubmitUpload").click(function (event) {
$("#divLoading").hide();
event.preventDefault();
getTempUpload(event);
});
});
function getTempUpload(event)
{
var formData = new FormData($('fileUpload')[0]);
$.ajax
({
type: 'POST',
async: false,
url: RootUrl + "DocumentUpload/fnUpload",
data: { fileNamearg: formData },
cache: false,
datatype: "Json",
success: function (data) {
if (data != "") {
alert(data);
}
},
error: function (error) {
alert('Error' + error.responseText);
}
});
}
</script>
In My model,
[FileTypes("pdf,jpg,jpeg,gif,tif,tiff,png")]
[DisplayName("File Upload")]
public virtual HttpPostedFileBase fileUpload { get; set; }
public string DocExtesnsion { get; set; }
public string DocPath { get; set; }
...
...
And Ajax method is,
public JsonResult fnUpload(HttpPostedFileBase fileNamearg, FormCollection frmcoll)
{
TrnMstDocUploadModel model=new TrnMstDocUploadModel();
String resultMsg = string.Empty;
model.fileUpload = fileNamearg;
if (model.FileNameArg != null)
{
if (Convert.ToString(ConfigurationManager.AppSettings["UploadFileSizeValidation"]).ToUpper() == "YES")
{
if ((fileNamearg.ContentLength / 1024) / 1024 > Convert.ToInt32(ConfigurationManager.AppSettings["UploadFileSize"].ToString()))
{
resultMsg = "Maximum File Size Exceeded " + ConfigurationManager.AppSettings["UploadFileSize"].ToString() + " MB.";
}
if (string.IsNullOrEmpty(resultMsg))
{
TempSave("", model, out resultMsg);
return Json(resultMsg,JsonRequestBehavior.AllowGet);
}
}
}
return Json("", JsonRequestBehavior.AllowGet);
}
The fnUpload method is working fine, but Here the problem is fileNamearg parameter is null. It is working when I tried it using form action and HttpPost methods. But I want to do it with Ajax. So how to pass the HttpPostedFileBase parameter to Ajax Method?. Please anybody help