Home > Enterprise >  ASP .NET MVC: Get the url and view the image as it changes
ASP .NET MVC: Get the url and view the image as it changes

Time:04-19

I have a function that allows me to edit an image but I want as soon as I click the Edit button I will get the URL of the current image image: enter image description here Do not see "no file chosen" I want the URL of the image to appear on the right Step Two Once I swap a picture I also want the picture to change to the picture I swap

My Service:

public class FileService : IFileService
{
private readonly IWebHostEnvironment _environment;
public FileService(IWebHostEnvironment environment)
{
    _environment = environment;
}
public async Task<string> File([FromForm] CreateAnimalViewModel model)
{
    string wwwPath = _environment.WebRootPath;
    var path = Path.Combine(wwwPath, "Images", model.Photo!.FileName);
    if (model.Photo.Length > 0)
    {
        using var stream = new FileStream(path, FileMode.Create);
        await model.Photo.CopyToAsync(stream);
    }
      return model.Animal!.PhotoUrl = model.Photo.FileName;
}

public interface IFileService
{
Task<string> File([FromForm] CreateAnimalViewModel model);
}

My ViewModel:

public class CreateAnimalViewModel
{
public Animal? Animal { get; set; }
public IFormFile Photo { get; set; }
}

My Controller:

public async Task<IActionResult> EditAnimal(int id)
{
    var animal = await _repo.FindAnimalById(id); 
    ViewBag.Category = new SelectList(_repository.GetCategoriesTable(), "CategoryId", "Name");
    return View(new CreateAnimalViewModel() { Animal = animal});
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditAnimal([FromForm] CreateAnimalViewModel model)
{
    ModelState.Clear();
    TryValidateModel(model);

    await _file.File(model);

    if (!ModelState.IsValid)
    {
        await _repo.EditAnimal(model.Animal!);
        return RedirectToAction(nameof(Manager));
    }
    return View();
}

My Repository:

 public async Task<int> AddAnimal(Animal animal)
{
    _context.Add(animal!);
    return await _context.SaveChangesAsync();
}

public async Task<int> EditAnimal(Animal animal)
{
    _context.Update(animal);
    return await _context.SaveChangesAsync();
}

public DbSet<Category> GetCategories()
{
    var category = _context.Categories;
    return category;
}

My View:

@model PetShop.Client.Models.CreateAnimalViewModel
    <form asp-action="EditAnimal" method="post" enctype="multipart/form-data">
    <div asp-validation-summary="ModelOnly"></div><input type="hidden" asp-for="Animal!.AnimalId" id="Space"/>
    <dl  >
    <dt class = "col-sm-2"><label asp-for="Animal!.Name" id="Space"></label></dt>
    <dd class = "col-sm-10"><input asp-for="Animal!.Name"/><span asp-validation-for="Animal!.Name" id="Validation"></span></dd>
    <dt class = "col-sm-2"><label asp-for="Animal!.BirthDate" id="Space"></label></dt>
    <dd class = "col-sm-10"><input asp-for="Animal!.BirthDate"/><span asp-validation-for="Animal!.BirthDate" id="Validation"></span></dd>
    <dt class = "col-sm-2"><label asp-for="Animal!.Description" id="Space"></label></dt>
    <dd class = "col-sm-10"><input asp-for="Animal!.Description"/><span asp-validation-for="Animal!.Description"></span>
    </dd> <dt class = "col-sm-2"><label asp-for="Animal!.CategoryId" id="Space"></label></dt>
    <dd class = "col-sm-10"><select asp-for="Animal!.CategoryId"asp-items="ViewBag.Category"></select>
    <span asp-validation-for="Animal!.CategoryId"></span></dd>
    <dt class = "col-sm-2"><label asp-for="Photo"></label></dt>
    <dd class = "col-sm-10"><input type="file" asp-for="Photo" accept="image/*"/>
        <img src="~/images/@Model.Animal!.PhotoUrl"
                         
                         height="50" width="75"
                         style="border:1px"
                         asp-append-version="true" accept="image/*" />
    <span asp-validation-for="Photo" id="ImageValidation"></span></dd>
    <br /> <br /><br/><input type="submit" value="Save" id="ButtonDesign"/>
</dl>
</form>
     <a asp-action="Commands"><input type="submit" value="Back to Admin Page" id="BackPageButton"/></a>

image: enter image description here

CodePudding user response:

You cannnot implement that:

I have gone through your code what you are trying to implement is to set intial value on input type="file" which is not possible due to security reason which you enter image description here

  • If the checkbox clicked then show the file upload option.

Note: Elementary Javascript required for that implementation

HTML:

<div>
    <form asp-action="EditAnimal" method="post" enctype="multipart/form-data">
        <div asp-validation-summary="ModelOnly"></div><input type="hidden" asp-for="Animal!.AnimalId" id="Space" />
        <div>
            <h4><strong>Animal Details</strong> </h4>

            <table >

                <tr>
                    <th> <label asp-for="Animal!.Name"></label></th>
                    <td> <input asp-for="Animal!.Name"  placeholder="Enter animal name" /><span asp-validation-for="Animal!.Name"></span></td>
                </tr>
                <tr>
                    <th> <label asp-for="Animal!.Description"></label></th>
                    <td> <input asp-for="Animal!.Description"  placeholder="Enter animal description" /><span asp-validation-for="Animal!.Description"></span></td>
                </tr>
                <tr>
                    <th> <label asp-for="Animal!.Category"></label></th>
                    <td> <input asp-for="Animal!.Category"  placeholder="Enter animal category" /><span asp-validation-for="Animal!.Category"></span></td>
                </tr>
                <tr>
                    <th> <label asp-for="Photo"></label></th>
                    <td>
                        <img src="~/images/@Model.Animal!.PhotoUrl"
                             
                             height="50" width="75"
                             style="border:1px"
                             asp-append-version="true" accept="image/*" />
                        <span><a href="@Model.ImageURL">@Model.ImageURL</a></span>
                        <input type="checkbox" id="CheckBoxId"  style="margin-top:16px;border:1px solid" /> <span><strong>Upload New File</strong></span>
                        <input type="file" name="photo" id="chooseFile" accept="image/*" />
                    </td>
                </tr>

                <tr>
                    <th> <label>Updated On Local Time</label></th>
                    <td> <input asp-for="Animal!.LocalTime"  disabled /><span asp-validation-for="Animal!.Category"></span></td>
                </tr>
                
                <tr>
                    <th>  <button type="submit"  style="width:107px">Update</button></th>
                    <td> </td>
                </tr>
                <tr>
                    <th>@Html.ActionLink("Back To List", "Index", new { /* id=item.PrimaryKey */ }, new { @class = "btn btn-success" })</th>
                    <td> </td>
                </tr>
            </table>
        </div>
    </form>

</div>

Javascript:

@section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
    $(document).ready(function () {
        //On Edit Page Load Hiding the upload option
        $("#chooseFile").hide();

        //When upload check box clicked showing the upload option
        $('#CheckBoxId').mousedown(function() {
            if (!$(this).is(':checked')) {
                 this.checked = true;
                $("#chooseFile").show();
            }
            else{
                $("#chooseFile").hide();
            }
        });

    });
</script>
}

Output:

enter image description here

Hope this would help you accordingly.

  • Related