asp.net-mvcasp.net-mvc-controller

Submitting form using controller method


I'm trying to call a method from view, but it's not working! :(

My Controller code:

public class ProfessionalController : Controller
{
    //
    // GET: /Professional/
    public ActionResult Index()
    {
        return View();
    }


    public ActionResult Sum(int nro1, int nro2)
    {
        var value = nro1 + nro2;

        ViewBag.SumResult = value;

        return View();
    }
}

My views code:

Professional Index:

@{
    ViewBag.Title = "Profissional";
}

<h2>Profissional</h2>


@using (Html.BeginForm("Professional", "Sum")) {

    <input id="nro1" type="number" class="form-control marged_top" placeholder="Numero 1" />
    <input id="nro2" type="number" class="form-control marged_top" placeholder="Numero 2" />


    <button id="Sum" name="Sum" value="Sum" class="btn btn-default" type="button"
            data-toggle="button">

        Sum
    </button>

}

Sum View:

@{
    ViewBag.Title = "Sum";
}

<h2>Sum</h2>


@ViewBag.SumResult;

Doesn't occurs any error, just nothing happens when i click at Sum button.


Solution

  • Some issues:

    Note that you are not "calling a Controller from a View" - you are submitting a form, which starts a new Controller-View cycle. Html.Action can do something similar, but that is not what you're trying to do here.

    I'd also take this opportunity and recommend against using ViewBag - Use a strongly typed view model instead