Frantisek Pastorek Frantisek Pastorek - 16 days ago 9
ASP.NET (C#) Question

Set path of selected file to model in view

I am trying to set the full path of the selected file into the model in the view.

Controller FileController:

public async Task<IActionResult> Create(CreateFileViewModel model)
{
if (ModelState.IsValid)
{
var file = new File
{
Path = model.Path
};
_context.Add(file);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(model);
}


Model CreateFileViewModel:

public class CreateFileViewModel
{
public string Path { get; set; }
}


Model File:

public class File
{
public int Id { get; set; }
public string Path { get; set; }
}


ViewForm Create:

<form asp-action="Create">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Path" class="control-label"></label>
<input asp-for="Path" id="selectedFile" type="file" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>


Script in Create:

<script>
document.getElementById('selectedFile').onmouseout = function () {
@Model.Path=this.value;
};
</script>


But

@Model.Path=this.value;


this not working. Ofc I cannot convert between razor and javascript variables. But I don't know another way how to set full path of selected file into the model variable.
This

<input asp-for="Path" id="selectedFile" type="file" />


set into model variable just file name, without a path.

Answer Source

@Model.Path is server side i.e. c# code, while this.value is java script code which is client side code, so the server side code will get executed when view is rendered while your js code with execute on particular event in your html.

What you need is to update the hidden value via javascript and it will post back in controller with updated value and will also work in html with the updated value.

Your hidden field will be rendered with id Path, so you can write :

document.GetElementById("Model").value = this.value;

or if you have jquery library included in your application, then you can make use of that as well:

$("#Path").val(this.value);

This way when the model will get posted back to controller, the Path property will have the updated value which would be the path you have assigned via js code.

Hope it helps!