Search code examples
asp.netpostmodel-view-controllergetviewmodel

ASP.Net button doesn't call Post method


I'm stuck at passing data from my view to my Details method, which sends the values to a mail method.

My view contains a form in which the user can put a comment. When pressing the send button, it sends the value in the form to the [Post] Details method, which in turn sends it to a sendMail method.

I've noticed that clicking the button does nothing but clear the form field. My guess is that something is wrong with the post method, since I'm not getting any errors, and while debugging I noticed the button doesn't call the Post method.

Form

@model Taijitan.Models.ViewModels.LessonDetailsViewModel
...
<form method="post">
    <div class="form-group">
        <label asp-for="Body"></label>
        <input asp-for="Body" class="form-control" id="Body" />
        <span asp-validation-for="Body" class="text-danger"></span>
    </div>
    <button class="btn btn-primary" type="submit">Send</button>
</form>

Get

public IActionResult Details(int id, int? sessionId, int? memberId)
        {
            Lesson lesson = _lessonRepository.GetBy(id);
            LessonDetailsViewModel ldvm = new LessonDetailsViewModel(lesson) { SessionId = sessionId, MemberId = memberId };

            return View(ldvm);
        }

Post

        [HttpPost]
        public IActionResult Details(LessonDetailsViewModel ldvm)
        {
            if (ModelState.IsValid)
            {
                string lessonTitle = ldvm.Lesson.Name;
                string mailBody = ldvm.Body;
                try
                {
                    SendMail(lessonTitel, mailBody);
                    TempData["message"] = $"Email sent";
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e.Message);
                    TempData["error"] = "Something went wrong...";
                    return RedirectToAction(nameof(Index));
                }
            }
            return RedirectToAction(nameof(Details), ldvm);
        }

Solution

  • Alexander's comment was the solution, had some problems with reusing a property, but a hiddenfor also fixed that, problem is solved now.