Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ASP.NET Web App CORE: the HttpPost Edit Method in Controller not being called

When i redirect to the Edit.cshtml page, only the HttpGet seems to be working. The HttpPost is not working. Which means that when I make changes and click on the Edit button on the Edit form, the HttpPost Edit is supposed to be invoked to call the PUT API. But the HttpGet Edit is called instead… What have I done wrong?

The HttpGet to retrieve the existing info

    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        await ViewBags();

        HttpResponseMessage response = await GlobalVariables.WebApiClient.GetAsync("article/detail/" + id.ToString());
        if (response.IsSuccessStatusCode)
        {
            var authorTagArticle = new AuthorTagArticle();
            authorTagArticle = response.Content.ReadAsAsync<AuthorTagArticle>().Result;
            var articleForm = new ArticleForm();
            articleForm.ArticleId = authorTagArticle.Article.ArticleId;
            articleForm.ArticleTitle = authorTagArticle.Article.ArticleTitle;
            articleForm.ArticleContent = authorTagArticle.Article.ArticleContent;
            articleForm.CreatedOn = authorTagArticle.Article.CreatedOn;
            articleForm.ImagePath = authorTagArticle.Article.ImagePath;
            articleForm.AuthorIds = authorTagArticle.Author.Select(e => e.UserId).ToArray();
            articleForm.TagIds = authorTagArticle.Tag.Select(e => e.TagId).ToArray();

            return View(articleForm);
        }
        else
        {
            TempData["error"] = "Error - Unable to open Edit Article Menu";
            return RedirectToAction("Index", "Home");
        }
    }

The HttpPost Edit method: to call the PUT API

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, ArticleForm articleForm)
{
    if (id != articleForm.ArticleId)
    {
        return NotFound();
    }

    //If Image is Updated
    var content = Request.Form.Files;
    const long MaxLength = 10485760; // 10MB
    string oldImagePath = articleForm.ImagePath;

    if (content.Count() > 0 && content.First().ContentType.Contains("image") && content.First().Length < MaxLength)
    {
        articleForm.ImagePath = "article/" + content.First().FileName;
    }
    else
    {
        ModelState.AddModelError("Image", "Please select a valid image less than 10MB");
    }

    if (ModelState.IsValid)
    {
        try
        {
            Article article = new Article();
            article.ArticleId = articleForm.ArticleId;
            article.ArticleTitle = articleForm.ArticleTitle;
            article.ArticleContent = articleForm.ArticleContent;
            article.CreatedOn = articleForm.CreatedOn;
            article.ImagePath = articleForm.ImagePath;

            HttpResponseMessage response = await GlobalVariables.WebApiClient.PutAsJsonAsync("article/edit/" + id, article);

            if (response.IsSuccessStatusCode)
            {
                TempData["success"] = "Article Updated!";
                return RedirectToAction("Index", "Article");
            }

            else
            {
                TempData["error"] = "Error - Unable to edit article!";
                return RedirectToAction("Index", "Home");
            }
        }
        catch (DbUpdateConcurrencyException) { }

    }
    return View(articleForm);
}

Edit.cshtml

@model SCANews_UI.Models.ArticleForm

@{ ViewData["Title"] = "Edit"; }

<h1>Edit Article</h1>

<div class="card" style="width: 70rem;">
    <div class="card-body">
        <form asp-action="Create" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="ArticleId" />
            <div class="form-group">
                <label asp-for="ArticleTitle" class="control-label"></label>
                <input asp-for="ArticleTitle" class="form-control">
                <span asp-validation-for="ArticleTitle" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ArticleContent" class="control-label"></label>
                <textarea asp-for="ArticleContent" id="testCK" class="form-control"></textarea>
                <span asp-validation-for="ArticleContent" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label asp-for="ImagePath" class="control-label"></label>
                <br />
                <img style="max-width: 100%; height: 200px;" src="@Model.ImagePath" class="rounded img-thumbnail" alt="Article Image" id="existingImage">
                <input hidden asp-for="ImagePath" class="form-control" />
                <div class="custom-file">
                    <input type="file" asp-for="ImagePath" onchange="readURL(this)" class="custom-file-input form-control" name="Image" id="customFile">
                    <label class="custom-file-label" for="customFile">Choose file</label>
                </div>
                <span asp-validation-for="ImagePath" class="text-danger"></span>
                <!-- Uploaded image area-->
                <div class="image-area mt-4"><img id="imageResult" src="#" alt="" class="img-fluid rounded shadow-sm mx-auto d-block"></div>
            </div>
            <div class="form-group">
                <input type="submit" value="Edit" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/ckeditor/ckeditor.js"></script>

<script>
    var contentTextArea = document.getElementById("testCK")
    CKEDITOR.replace(contentTextArea);
</script>

<script type="text/javascript">
    $(".custom-file-input").on("change", function () {
        var fileName = $(this).val().split("\\").pop();
        $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
    });
</script>

<script>
    //Show Image
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#imageResult')
                    .attr('src', e.target.result);
            };
            reader.readAsDataURL(input.files[0]);
        }
        var beforeImage = document.getElementById('existingImage');
        beforeImage.style.display = 'none';
    }

    $(function () {
        $('#customFile').on('change', function () {
            readURL(input);
        });
    });
</script>

<script type="text/javascript">
    //Show Image Name
    document.querySelector('.custom-file-input').addEventListener('change', function (e) {
        var name = document.getElementById("customFile").files[0].name;
        var nextSibling = e.target.nextElementSibling
        nextSibling.innerText = name
    })
</script>

ArticleForm model

public class ArticleForm
{
    public int ArticleId { get; set; }

    [Required, Column(TypeName = "varchar(150)")]
    [DisplayName("Article Title")]
    public string ArticleTitle { get; set; }

    [Required, Column(TypeName = "text")]
    [DisplayName("Article Content")]
    public string ArticleContent { get; set; }

    public DateTime CreatedOn { get; set; }

    [Column(TypeName = "text")]
    [DisplayName("Image")]
    public string ImagePath { get; set; }

    public int[] AuthorIds { get; set; }

    public int[] TagIds { get; set; }
}

Article Model

public class Article
{
    public int ArticleId { get; set; }

    public string ArticleTitle { get; set; }

    public string ArticleContent { get; set; }

    public DateTime CreatedOn { get; set; }

    public string ImagePath { get; set; }
}

AuthorTagArticle Model

public class AuthorTagArticle
{
    public Article Article { get; set; }

    public List<User> Author { get; set; }

    public List<Tag> Tag { get; set; }
}

GlobalVariables

public class GlobalVariables
{
    public static HttpClient WebApiClient = new HttpClient();

    static GlobalVariables()
    {
        //local testing
        WebApiClient.BaseAddress = new Uri("https://localhost:44361/api/");

        //lambda APIs


        WebApiClient.DefaultRequestHeaders.Clear();
        WebApiClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    }
}

>Solution :

Try to edit your code as following: <form asp-controller="{Your controller}" asp-action="Edit" method="post">

Also you can read some info about Tag Helpers here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading