I want to have image upload in my page and I have this.
@using (Html.BeginForm())
{
<img id="sp" src="/Student/RetrieveImage" alt="Photo" height=100 width=200 />
<input type="file" name="ImageData" id="ImageData" onchange="DI()" value="Upload" />
<input type="submit" name="submitButton" id="submitButton" value="Upload" formaction="/Student/Upload" formmethod="post" class="btn btn-primary" />
}
The image is updated as user selects a file using the javascript function DI(). This works fine.
<script>
function DI() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("ImageData").files[0]);
oFReader.onload = function (oFREvent) { document.getElementById("sp").src = oFREvent.target.result };
};
$(document).ready(function () {
$('.ImageData').change(function () {
$('.path').text($(this).files[0].name);
});
});
</script>
@Html.TextBoxFor(model => model.Photo, new { htmlAttributes = new { @class = "form-control", @id="path"} })
What is not working is, I want to bind the name of the file selected to the TextBoxFor helper for the photo field so that I can save it to the database. It is better to bind the file name to the photo field without setting the value to a the TextBoxFor helper if that is possible. How can I achieve this? And if I have to set the value for the TextBoxFor helper, how can I do that? The jquery I wrote is not working.
id="path"is an input which does not have a.text()property - it would need to be$('.path').val($(this).files[0].name);. But its unclear what you trying to do here - why are you not just getting the file name in the POST method when you upload the file?FileNameproperty ofHttpPostedFileBase), so what is the point of this?$(this)[0].files[0].name