简体   繁体   中英

Calling a Controller Method with parameters from a View when a button is clicked (cshtml, c#, MVC)

This is my Controller, where I would like to call the method AnswerASelect.

namespace VotingWebApp.Controllers
{
   public class HomeController : Controller
   {

    public async Task<IActionResult> Home()
    {
        return View(await _context.QuestionItem.ToListAsync());
    }

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

        var questionItem = await _context.QuestionItem.SingleOrDefaultAsync(m => m.ID == id);
        if (questionItem == null)
        {
            return NotFound();
        }

        return View(questionItem);
    }


    public async Task<IActionResult> AnswerASelect(int? id)
    {
        var questionItem = await _context.QuestionItem.SingleOrDefaultAsync(m => m.ID == id);
        questionItem.AnswerAVote = questionItem.AnswerAVote + 1;
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }

This is my View where on the button click I would like to call the AnswerASelect method with the model as the parameter, something like... AnswerASelect(model)

@model VotingWebApp.Models.QuestionItem

 @{
  ViewData["Title"] = "Answer Question";
 }

 <h2>@Html.DisplayFor(model => model.Question)</h2>


 <div class="container">
    <button type="button" class="btn btn-info btn-lg" onclick= "CALL AnswerASelect(Model)">@Html.DisplayFor(model => model.AnswerA)</button>

I was hoping to find a simple solution, thank you very much in advance. I'm new to Web App development and I am finding this difficult to learn. I have seen a few posts similar but I don't really have a good understanding of them, making it hard to apply the solution to my current problem.

 <h4 class="card-title addbutton">
        <button type="button" onclick="CreateModelDialog('@Url.Action("Create", "Controller",new {restaruntId =Model.RestaurantId})')" class="btn btn-info btn-rounded m-t-10  modal-link">Add</button>
    </h4>

  function CreateModelDialog(url) {
            debugger
            $(".modal-backdrop").remove();
            $('#modal-container').html("");
            $(".modal-backdrop").show();
            $(".stream-loader").show();
            $.get(url, function (data) {

                $(".stream-loader").hide();
                $('#modal-container').html("");
                $('#modal-container').html(data);
                debugger
                $('#modal-container').attr("style", "display:block !important");
            });
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM