Owais Ahmed Owais Ahmed - 15 days ago 8
C# Question

Assigning JavaScript value to mvc model property

I am using asp.net mvc application and trying to upload an image.

This is uploading image function

$(document).ready(function () {

TableDatatablesEditable.init();
$("#UploadImg").change(function () {
var data = new FormData();
var files = $("#UploadImg").get(0).files;
if (files.length > 0) {
data.append("MyImages", files[0]);
}

$.ajax({
url: "@Url.Action("UploadFile")",
type: "POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
$("#HeaderInput").text('/Upload/' + response);

$("#imgPreview").attr('src', '/Upload/' + response);
},
error: function (er) {
alert(er);
}

});
});
});


Here i am displaying the uploaded image


@Html.Label("Logo Upload", new { @class = "col-md-3 control-label" })

<div class="col-md-7">
<input type="file" class = "col-md-3 control-label" id="UploadImg" value="@Model.FundDetail.ImagePath" name="@Model.FundDetail.ImagePath" /> <br /><br />
<br />
</div>
</div>


The image uploading is working fine but values are not assigning to the model's property
"@Model.FundDetail.ImagePath"


How can i assign value from javascript. Can anyone suggest me how to do this.

Thanks in advance

Answer

You cannot set the value attribute of a file input for security reasons. The only way it can be set is by the user selecting a file in the browser.

In your form, include a hidden input for the file name

@Html.HiddenFor(m => m.FundDetail.ImagePath)

and change the file input to

<input type="file" class = "col-md-3 control-label" id="UploadImg" />

Then in the ajax call where you upload the file and return the saved path, update the value of the hidden input in the success callback

$.ajax({
    ....
    success: function (response) {
        $("#HeaderInput").text('/Upload/' + response);
        $("#imgPreview").attr('src', '/Upload/' + response);
        // Set the value of the hidden input
        $('#FundDetail_ImagePath').val(response);
    },
    ....
});

Now when your submit the form, the ImagePath property will be populated with the saved path of the file which can then be saved to the database.